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

LeetCode: Partition List

时间:2014-09-02 00:05:33      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   io   strong   ar   for   

LeetCode: 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.

地址:https://oj.leetcode.com/problems/partition-list/

算法:首先,找到第一个大于等于x的节点,记其前趋节点为pre,则在继续往后遍历,若发现比x小的值,则把该节点从链表中移出来,插入到pre节点后面。代码:

 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         if(!head)   return NULL;
13         ListNode *p = head;
14         ListNode *pre = NULL;
15         while(p && p->val < x){
16             pre = p;
17             p = p->next;
18         }
19         if(!p)
20             return head;
21         ListNode *q = NULL;
22         while(p->next){
23             if(p->next->val < x){
24                 q = p->next;
25                 p->next = q->next;
26                 if(pre){
27                     q->next = pre->next;
28                     pre->next = q;
29                     pre = q;
30                 }else{
31                     q->next = head;
32                     head = q;
33                     pre = q;
34                 }
35             }else{
36                 p = p->next;
37             }
38         }
39         return head;
40     }
41 };

 

LeetCode: Partition List

标签:des   style   blog   http   color   io   strong   ar   for   

原文地址:http://www.cnblogs.com/boostable/p/leetcode_partition_list.html

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