首页 > 其他 > 详细

LeetCode() Partition List

时间:2015-11-29 16:19:27      阅读:256      评论:0      收藏:0      [点我收藏+]
/**
 * 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* head1=new ListNode(0);
        ListNode* head2=new ListNode(0);
        ListNode* t1,*t2;
        head1->next=head;
        head2->next=head;
        t1=head1,t2=head2;
        while(head)
        {
			ListNode* tem;
            if(head->val < x)
            {                
                tem=head;
                t1->next=tem;
                t1=t1->next;             
            }
            else
            {
                tem=head;
                t2->next=tem;
                t2=t2->next;
            }
            head=head->next;
        }
        t2->next=NULL; //必须要加上这句,否则可能是死循环。
        t1->next=head2->next;
        return head1->next;
    }
};

  

LeetCode() Partition List

原文:http://www.cnblogs.com/yanqi110/p/5004850.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!