首页 > 其他 > 详细

LeetCode86 Partition List

时间:2016-10-13 23:49:59      阅读:241      评论:0      收藏:0      [点我收藏+]

题目:

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.(Medium)

For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.

分析:

把链表归并,其思路就是先开两个链表,把小于x的值接在链表left后面,大于x的值接在链表right后面;

然后把链表left的尾部与链表right的头部接在一起。

注意:链表right的尾部next赋值为nullptr。

代码:

 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 dummy1(0);
13         ListNode dummy2(0);
14         ListNode* left = &dummy1;
15         ListNode* right = &dummy2;
16         while (head != nullptr) {
17             if (head -> val < x) {
18                 left -> next = head;
19                 left = left -> next;
20             }
21             else {
22                 right -> next = head;
23                 right = right -> next;
24             }
25             head = head -> next;
26         }
27         left -> next = dummy2.next;
28         right -> next = nullptr;
29         return dummy1.next;
30     }
31 };

 

 

LeetCode86 Partition List

原文:http://www.cnblogs.com/wangxiaobao/p/5958421.html

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