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

思考:遍历链表,小于x的存于链表head1,大于等于的存于链表head2,合并head1,head2.

/**
 * 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 head;
        ListNode *p=head;
        ListNode *head1=NULL;
        ListNode *head2=NULL;
        ListNode *p1,*p2;
        while(p)
        {
            ListNode *node=new ListNode(p->val);
            if(node->val<x) 
            {
                if(head1==NULL) 
                {
                    head1=p1=node;
                }
                else
                {
                    p1->next=node;
                    p1=node;
                }
            }
            else
            {
                if(head2==NULL) 
                {
                    head2=p2=node;
                }
                else
                {
                    p2->next=node;
                    p2=node;
                }
            }
            p=p->next;
        }
        p1->next=head2;
        if(head1==NULL) return head2;
        return head1;
    }
};

  

posted @ 2013-12-04 20:37  七年之后  阅读(209)  评论(0编辑  收藏  举报