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.

思路:划分链表结构,大于等于目标值移到链表尾部,并更新链表,小于目标值则不动。此题使用使用四个指针来定位链表结构,pPre指向该节点的前一个结点,pLeft代表当前结点,pRight代表移动前的链表尾指针,tail代表时刻更新的链表尾部。首先pLeft向尾部移动,如果该节点值大于等于目标值,则将该节点移到链表尾部,更新pPre和tail,反之pPre=pLeft,pLeft=pLeft->next;最后要注意的是pRight移动前的链表尾结点,该值是否大于等于目标值,如果是,在进行移动,如果不是,没有作为。

/**
 * 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) {
        if(head==NULL)
            return NULL;
        ListNode *pPre=NULL;
        ListNode *pLeft=head;
        ListNode *pRight=head;
        while(pRight->next)
        {
            pRight=pRight->next;
        }
        ListNode *pTail=pRight;
        while(pLeft!=pRight)
        {
            if(pLeft->val>=x)
            {
                ListNode *pNext=pLeft->next;
                if(head==pLeft)
                    head=pNext;
                pTail->next=pLeft;
                pLeft->next=NULL;
                pTail=pLeft;
                if(pPre)
                    pPre->next=pNext;
                pLeft=pNext;
            }
            else
            {
                pPre=pLeft;
                pLeft=pLeft->next;
            }
        }
        if(pLeft->val>=x && pRight!=pTail)
        {
            ListNode *pNext=pLeft->next;
            if(head==pLeft)
                head=pNext;
            pTail->next=pLeft;
            pLeft->next=NULL;
            if(pPre)
                pPre->next=pNext;
        }
        return head;
    }
};

 

posted @ 2014-04-24 13:48  Awy  阅读(159)  评论(0编辑  收藏  举报