[LeetCode] Partition List 划分鏈表


 

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.

 

這道題要求我們划分鏈表,把所有小於給定值的節點都移到前面,大於該值的節點順序不變,相當於一個局部排序的問題。那么可以想到的一種解法是首先找到第一個大於或等於給定值的節點,用題目中給的例子來說就是先找到4,然后再找小於3的值,每找到一個就將其取出置於4之前即可,代碼如下:

解法一

class Solution {
public:
    ListNode *partition(ListNode *head, int x) {
        ListNode *dummy = new ListNode(-1);
        dummy->next = head;
        ListNode *pre = dummy, *cur = head;;
        while (pre->next && pre->next->val < x) pre = pre->next;
        cur = pre;
        while (cur->next) {
            if (cur->next->val < x) {
                ListNode *tmp = cur->next;
                cur->next = tmp->next;
                tmp->next = pre->next;
                pre->next = tmp;
                pre = pre->next;
            } else {
                cur = cur->next;
            }
        }
        return dummy->next;
    }
};

 

 

這種解法的鏈表變化順序為:

1 -> 4 -> 3 -> 2 -> 5 -> 2 

1 -> 2 -> 4 -> 3 -> 5 -> 2 

1 -> 2 -> 2 -> 4 -> 3 -> 5

 

此題還有一種解法,就是將所有小於給定值的節點取出組成一個新的鏈表,此時原鏈表中剩余的節點的值都大於或等於給定值,只要將原鏈表直接接在新鏈表后即可,代碼如下:

解法二

 

class Solution {
public:
    ListNode *partition(ListNode *head, int x) {
        if (!head) return head;
        ListNode *dummy = new ListNode(-1);
        ListNode *newDummy = new ListNode(-1);
        dummy->next = head;
        ListNode *cur = dummy, *p = newDummy;
        while (cur->next) {
            if (cur->next->val < x) {
                p->next = cur->next;
                p = p->next;
                cur->next = cur->next->next;
                p->next = NULL;
            } else {
                cur = cur->next;
            }
        }
        p->next = dummy->next;
        return newDummy->next;
    }
};

 

此種解法鏈表變化順序為:

Original: 1 -> 4 -> 3 -> 2 -> 5 -> 2 

New:

 

Original: 4 -> 3 -> 2 -> 5 -> 2 

New:   1

 

Original: 4 -> 3 -> 5 -> 2 

New:   1 -> 2

 

Original: 4 -> 3 -> 5 

New:   1 -> 2 -> 2

 

Original: 

New:   1 -> 2 -> 2 -> 4 -> 3 -> 5 

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM