首页 > 其他 > 详细

LeetCode OJ--Partition List

时间:2014-02-14 22:41:57      阅读:376      评论:0      收藏:0      [点我收藏+]

http://oj.leetcode.com/problems/partition-list/

链表的处理

bubuko.com,布布扣
#include <iostream>
using namespace std;
 
struct ListNode {
     int val;
     ListNode *next;
     ListNode(int x) : val(x), next(NULL) {}
 };
 
class Solution {
public:
    ListNode *partition(ListNode *head, int x) {
        ListNode *head1 = NULL,*head2 = NULL,*tail1 = NULL,*tail2 = NULL,*p = NULL;
        p = head;
        bool flag1 = 0,flag2 = 0;
        while(p)
        {
            if(p->val<x)
            {
                if(flag1 == 0)
                {
                    head1 = tail1 = p;
                    flag1 = 1;
                }
                else
                {
                    tail1->next = p;
                    tail1 = p;
                }
            }
            else
            {
                if(flag2 == 0)
                {
                    head2 = tail2 = p;
                    flag2 = 1;
                }
                else
                {
                    tail2->next = p;
                    tail2 = p;
                }
            }
            p = p->next;
        }
        if(head1 == tail1 && tail1 == NULL)
            return head2;
        tail1->next = head2;
        if(tail2)
        tail2->next = NULL;
        return head1;

    }
};

int main()
{
    ListNode *n1 = new ListNode(1);
    ListNode *n2 = new ListNode(4);
    ListNode *n3 = new ListNode(3);
    ListNode *n4 = new ListNode(2);
    ListNode *n5 = new ListNode(5);
    ListNode *n6 = new ListNode(2);
    n1->next = n2;
    n2->next = n3;
    n3->next = n4;
    n4->next = n5;
    n5->next = n6;
    ListNode *ans;
    Solution myS;
    ans = myS.partition(NULL,6);
    return 0;
}
bubuko.com,布布扣

LeetCode OJ--Partition List

原文:http://www.cnblogs.com/qingcheng/p/3548748.html

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