[LeetCode] 86 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.

解题思路:

一:

用两个指针遍历表,其中p指针用于寻找小于x的点,pre用于管理链表,该题主要考察对链表的基本操作;

1.创建头结点

image

2.寻找<x的点

找到后将该节点移动到pre->next;pre向后移动一步;

3.继续寻找

二:

创建两个链表一个存储小于x的元素 一个存储大于x的元素,最终小的链表尾部连接大的链表

 

代码1:

/**
 * 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||head->next==NULL)return head;
        ListNode* e=new ListNode(0);
        e->next=head;
        ListNode* pre=e;
        ListNode* p=e;
        ListNode* pnext;
        while(p!=NULL)
        {
            while(p->next!=NULL&&p->next->val>=x)
                p=p->next;
            if(p->next==pre->next)//未移动,发现小于元素,pre=pre->next
            {
                p=p->next;
                pre=pre->next;
            }
            else                    //移动,发现小于元素或发现空
            {
                if(p->next==NULL)
                {
                    return e->next;
                }
                else
                {
                    pnext=p->next;
                    p->next=pnext->next;
                    pnext->next=pre->next;
                    pre->next=pnext;
                    pre=pre->next;
                    p=pre;
                }
            }
        }
        return e->next;
    }
};

代码2:

/**
 * 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||head->next==NULL)return head;
        ListNode* e1=new ListNode(0);
        ListNode* e2=new ListNode(0);
        ListNode* pre1=e1;
        ListNode* pre2=e2;
        ListNode* p=head;
        while(p!=NULL)
        {
            if(p->val<x)
            {
                pre1->next=p;
                p=p->next;
                pre1=pre1->next;
                pre1->next=NULL;
            }
            else
            {
                pre2->next=p;
                p=p->next;
                pre2=pre2->next;
                pre2->next=NULL;
            }
        }
        pre1->next=e2->next;
        return e1->next;
    }
};
posted @ 2015-03-11 14:14  aorora  阅读(140)  评论(0编辑  收藏  举报