码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】Partition List

时间:2014-06-07 06:24:57      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:des   c   style   class   blog   code   

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小的(头newl, 尾left),一个记录不小于x的(头newr,尾right)。

扫描一遍链表,根据大小装入上述两个链表,最后将上述两个连起来即可。需要注意的是,最后一个节点的next需要设为NULL。

bubuko.com,布布扣
class Solution {
public:
    ListNode *partition(ListNode *head, int x) {
        ListNode *left = NULL;
        ListNode *right = NULL;
        ListNode *newl = left;
        ListNode *newr = right;

        while(head != NULL)
        {
            if(head->val < x)
            {
                if(left == NULL)
                {
                    left = head;
                    newl = left;
                }
                else
                {
                    left->next = head;
                    left = left->next;
                }
            }
            else
            {
                if(right == NULL)
                {
                    right = head;
                    newr = right;
                }
                else
                {
                    right->next = head;
                    right = right->next;
                }
            }
            head = head->next;
        }

        if(newl == NULL)
            return newr;
        else
        {
            if(right != NULL)
                right->next = NULL;
            left->next = newr;
            return newl;
        }
    }
};
bubuko.com,布布扣

bubuko.com,布布扣

【LeetCode】Partition List,布布扣,bubuko.com

【LeetCode】Partition List

标签:des   c   style   class   blog   code   

原文地址:http://www.cnblogs.com/ganganloveu/p/3770697.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!