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

LeetCode86 Partition List

时间:2016-10-13 23:50:47      阅读:141      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!