【LeetCode】86. Partition List

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.

 

维护两个链表,一个记录比x小的(头newhead1, 尾newtail1),一个记录不小于x的(头newhead2,尾newtail2)。

扫描一遍链表,根据大小装入上述两个链表,最后将上述两个连起来即可。

注意:newtail2的next需要设为NULL。

/**
 * 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) {
        ListNode* newhead1 = new ListNode(-1);
        ListNode* newtail1 = newhead1;
        ListNode* newhead2 = new ListNode(-1);
        ListNode* newtail2 = newhead2;
        while(head != NULL)
        {
            if(head->val < x)
            {
                newtail1->next = head;
                newtail1 = newtail1->next;
            }
            else
            {
                newtail2->next = head;
                newtail2 = newtail2->next;
            }
            head = head->next;
        }
        newtail2->next = NULL;
        newtail1->next = newhead2->next;
        return newhead1->next;
    }
};

posted @ 2014-06-05 16:59  陆草纯  阅读(242)  评论(0编辑  收藏  举报