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

【Leetcode】Partition List

时间:2014-05-22 03:53:29      阅读:313      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   class   c   code   

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.

bubuko.com,布布扣
 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode * partition(ListNode *head, int x) {
12         ListNode dummy_left(-1), dummy_right(-1);
13         ListNode *pl = &dummy_left, *pr = &dummy_right;
14         for (ListNode * p = head; p != nullptr; p = p->next) {
15             if (p->val < x) {
16                 pl->next = p;
17                 pl = pl->next;
18             } else {
19                 pr->next = p;
20                 pr = pr->next;
21             }
22         }
23         pl->next = dummy_right.next;
24         pr->next = nullptr;
25         return dummy_left.next;
26     }
27 };
View Code

维护两个链表,一个保存小于x的部分,一个保存大于x的部分,最后将两个链表拼接起来。要求保持稳定性则应该用尾插法。加dummy元素可使代码变简单。

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

【Leetcode】Partition List

标签:des   style   blog   class   c   code   

原文地址:http://www.cnblogs.com/dengeven/p/3738570.html

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