148 sort list
https://leetcode.com/problems/sort-list/
merge sortๅพๅฅฝๅ ๆณจๆmerge sortๆจกๆฟ๏ผdummy nodeๅจmerge็ๆถๅ็ๅบ็จ๏ผไปฅๅfind mid็ๅๆณ
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode mid = getMid(head);
ListNode left = head;
ListNode right = mid.next;
mid.next = null;
return merge(sortList(left), sortList(right));
}
private ListNode getMid(ListNode head) {
if (head == null) {
return null;
}
ListNode slow = head;
ListNode fast = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
private ListNode merge(ListNode n1, ListNode n2) {
ListNode dummy = new ListNode(-1);
ListNode cur = dummy;
while (n1 != null && n2 != null) {
if (n1.val <= n2.val) {
cur.next = n1;
cur = cur.next;
n1 = n1.next;
} else {
cur.next = n2;
cur = cur.next;
n2 = n2.next;
}
}
while (n1 != null) {
cur.next = n1;
cur = cur.next;
n1 = n1.next;
}
while (n2 != null) {
cur.next = n2;
cur = cur.next;
n2 = n2.next;
}
return dummy.next;
}
}
Last updated