【テクニック】LeetCode 86.Partition List


LeetCode 86. Partition List
Solution 1:私の答え、時間複雑度O(n)O(n)、空間複雑度O(n)O(n)
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        struct ListNode* smallHead = new ListNode(-1), *bigHead = new ListNode(-1), *cur = head;
        struct ListNode* smalltemp = smallHead, *bigtemp = bigHead;
        while (cur) {
            if (cur->val < x) {
                smalltemp->next = new ListNode(cur->val);
                smalltemp = smalltemp->next;
            }
            else {
                bigtemp->next = new ListNode(cur->val);
                bigtemp = bigtemp->next;
            }
            cur = cur->next;
        }
        smalltemp->next = bigHead->next;
        return smallHead->next;
    }
};

Solution 2:参考URL:http://www.cnblogs.com/grandyang/p/4321292.html参考になるテクニック!!!ヘッドノードを追加し,ノードのコピー操作を巧みに回避し,時間的複雑度は変化しなかったが,空間的複雑度はO(1)O(1)O(1)
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;
    }
};