标签:rtl nod turn val tco 判断 链表 new link
递归的算法很巧妙.
算法思想:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* sortList(ListNode* head) {
if(head == nullptr || head->next == nullptr) return head;
// 寻找中点
ListNode * fast = head->next; ListNode *slow = head;
while(fast != nullptr && fast->next != nullptr) {
slow = slow->next;
fast = fast->next->next;
}
ListNode *tmp = slow->next; // 断开两段
slow->next = nullptr;
ListNode * left = sortList(head);
ListNode * right = sortList(tmp);
ListNode * h = new ListNode(0); // 虚头
ListNode * res = h;
while(left != nullptr && right != nullptr){
if(left->val < right-> val) {
h->next = left;
left = left->next;
} else {
h->next = right;
right = right->next;
}
h = h->next; // 进行合并, h 和 left 或 right 同步合并
}
h->next = left != nullptr ? left : right;
return res->next;
}
};
/**
* 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 fast = head.next, slow = head;
while(fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode tmp = slow.next;
slow.next = null;
ListNode left = sortList(head);
ListNode right = sortList(tmp);
ListNode h = new ListNode(0);
ListNode res = h;
while(left != null && right != null) {
if(left.val < right.val) {
h.next = left;
left = left.next;
} else {
h.next = right;
right = right.next;
}
h = h.next;
}
h.next = left != null ? left : right;
return res.next;
}
}
标签:rtl nod turn val tco 判断 链表 new link
原文地址:https://www.cnblogs.com/eat-too-much/p/14866970.html