C++實現LeetCode(86.劃分鏈表)

[LeetCode] 86.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 

到此這篇關於C++實現LeetCode(86.劃分鏈表)的文章就介紹到這瞭,更多相關C++實現劃分鏈表內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: