https://leetcode.com/problems/sort-list/
解题思路:
这里选择归并排序,顺便能用到 Merge Two Sorted 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 slow = head;
ListNode fast = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode head1 = head;
ListNode head2 = slow.next;
slow.next = null;
head1 = sortList(head1);
head2 = sortList(head2);
return mergeTwoLists(head1, head2);
}
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null && l2 == null) return null;
ListNode dummy = new ListNode(0);
ListNode prev = dummy;
while (l1 != null && l2 != null) {
if (l1.val <= l2.val) {
prev.next = l1;
l1 = l1.next;
} else {
prev.next = l2;
l2 = l2.next;
}
prev = prev.next;
}
if (l1 != null) prev.next = l1;
if (l2 != null) prev.next = l2;
return dummy.next;
}
}