首页 > 代码库 > [LeetCode] 148. Sort List
[LeetCode] 148. Sort List
https://leetcode.com/problems/sort-list/
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode sortList(ListNode head) { if (head == null || head.next == null) { return head; } ListNode mid = findMiddle(head); ListNode head2 = sortList(mid.next); mid.next = null; ListNode head1 = sortList(head); return merge(head1, head2); } public ListNode merge(ListNode head1, ListNode head2) { ListNode dummy = new ListNode(-1); ListNode head = dummy; while (head1 != null && head2 != null) { if (head1.val < head2.val) { head.next = head1; head1 = head1.next; } else { head.next = head2; head2 = head2.next; } head = head.next; } while (head1 != null) { head.next = head1; head1 = head1.next; head = head.next; } while (head2 != null) { head.next = head2; head2 = head2.next; head = head.next; } return dummy.next; } public ListNode findMiddle(ListNode head) { ListNode fast = head; ListNode slow = head; while (fast.next != null && fast.next.next != null) { fast = fast.next.next; slow = slow.next; } return slow; } }
[LeetCode] 148. Sort List
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。