【技巧】LeetCode 86. Partition List

LeetCode 86. Partition List

Solution1:
我的答案,时间复杂度 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;
    }
};

Solution2:
参考网址:http://www.cnblogs.com/grandyang/p/4321292.html
值得借鉴的技巧!!!
加了一个头结点,巧妙地避免了复制结点的操作,时间复杂度没变,但空间复杂度降为 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;
    }
};

你可能感兴趣的:(LeetCode练习题,LeetCode,Partition,List)