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

Partition List

时间:2014-08-21 20:58:34      阅读:244      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   使用   os   io   for   

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部分的尾部。若当前值小于x,则将其插到小于x部分的链表的尾部;否则,将其插入到不小于x部分的链表的尾部。

 1 class Solution {
 2 public:
 3     ListNode *partition( ListNode *head, int x ) {
 4         if( !head || !head->next ) { return head; }
 5         ListNode *prev = 0, *post = head;
 6         while( post && post->val < x ) {
 7             prev = post;
 8             post = post->next;
 9         }
10         while( post && post->next ) {
11             if( post->next->val < x ) {
12                 ListNode *tmp = post->next;
13                 post->next = tmp->next;
14                 if( prev ) {
15                     tmp->next = prev->next;
16                     prev->next = tmp;
17                     prev = tmp;
18                 } else {
19                     tmp->next = head;
20                     head = prev = tmp;
21                 }
22             } else {
23                 post = post->next;
24             }
25         }
26         return head;
27     }
28 };

 

Partition List,布布扣,bubuko.com

Partition List

标签:des   style   blog   color   使用   os   io   for   

原文地址:http://www.cnblogs.com/moderate-fish/p/3925835.html

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