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