LeetCode刷題記125-148. 排序連結串列

鹹蛋黃麥芽糖小餅乾發表於2020-12-10

LeetCode刷題記125

148. 排序連結串列

題目
在這裡插入圖片描述

/**
 * 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 merge(ListNode p1, ListNode p2) {
        if (p1 == null) return p2;
        if (p2 == null) return p1;
        ListNode _p1 = p1;
        ListNode _p2 = p2;
        ListNode pre_p1 = null;
        while (p1 != null && p2 != null) {
            if (p1.val < p2.val) {
                if (p1.next != null) {
                    if (p1.next.val >= p2.val) {
                        ListNode tmp = p2.next;
                        p2.next = p1.next;
                        p1.next = p2;
                        p2 = tmp;
                    }
                    pre_p1 = p1;
                    p1 = p1.next;
                } else {
                    p1.next = p2;
                    return _p1;
                }
            } else {
                ListNode tmp = p2.next;
                p2.next = p1;
                if (pre_p1 != null) {
                    pre_p1.next = p2;
                }
                if (p1 == _p1) {
                    _p1 = p2;
                }
                pre_p1 = p2;
                p2 = tmp;
            }
        }
        return _p1;
    }
    public ListNode sortList(ListNode head) {
        if(head==null || head.next==null) return head;
        ListNode slow = head; //慢指標
        ListNode fast = head.next; //快指標
        
        while(fast!=null && fast.next!=null){ //快慢指標找到連結串列中點
            slow = slow.next; //慢指標走一步
            fast = fast.next.next; //快指標走兩步
        }
        ListNode rightHead = slow.next; //連結串列第二部分的頭節點
        slow.next = null; //cut 連結串列
        
        ListNode left = sortList(head); //遞迴排序前一段連結串列
        ListNode right = sortList(rightHead); //遞迴排序後一段連結串列
        return merge(left,right);
    }
}

1/3
125/150

相關文章