[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.

 

Hide Tags
 Linked List Two Pointers
 
思路:双指针,一个指向less,一个指向great,按顺序处理,注意lessNodeHea和greatNodeHead的应用。
/**
 * 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 lessNodeHead(-1);
            ListNode greatNodeHead(-1);

            ListNode *pLess = &lessNodeHead;
            ListNode *pGreat = &greatNodeHead;

            while(head)
            {
                if(head->val < x)
                {
                    pLess->next = head;
                    pLess = head;
                }
                else
                {
                    pGreat->next = head;
                    pGreat = head;
                }
                head = head->next;
            }

            pLess->next = greatNodeHead.next;
            pGreat->next = NULL;
            return lessNodeHead.next;

         }
 };

 

posted @ 2015-03-19 15:40  穆穆兔兔  阅读(129)  评论(0编辑  收藏  举报