首页 > 技术文章 > LeetCode86 Partition List

wangxiaobao 2016-10-13 22:25 原文

题目:

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 };

 

 

推荐阅读