[leetcode] Partition List

来源:互联网 发布:淘宝手机充话费 编辑:程序博客网 时间:2024/05/16 17:10

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和小于x的结点拼接到两条链后面,然后将两条链连在一起,返回连接在一起之后的头结点

代码:

/** * 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;        if(head->next==NULL) return head;        ListNode *start1=NULL,*start2=NULL;        ListNode *p1=NULL,*p2=NULL;        ListNode *temp=head;        while(temp!=NULL){            if(temp->val<x){                if(start1==NULL){                    start1=temp;                    p1=temp;                }                else{                    p1->next=temp;                    p1=p1->next;                }            }            if(temp->val>=x){                if(start2==NULL){                    start2=temp;                    p2=temp;                }                else{                    p2->next=temp;                    p2=p2->next;                }            }            temp=temp->next;        }        if(start1!=NULL){            if(start2!=NULL)             {                p1->next=start2;                p2->next=NULL;            }            else p1->next=NULL;            return start1;        }        if(start1==NULL){            p2->next==NULL;            return start2;        }    }};


0 0