86. 分隔链表

给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。你应当保留两个分区中每个节点的初始相对位置。

Example:

给定 head = 1->4->3->2->5->2, x = 3。

你应该返回 1->2->2->4->3->5。

Solution1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
//创建两个头结点
ListNode less_head(0);
ListNode more_head(0);
ListNode *less_ptr = &less_head;
ListNode *more_ptr = &more_head;
while(head){
//将val小于x的分进less_ptr,大于等于的分进more_ptr;
if(head->val < x){
less_ptr->next = head;
less_ptr = less_ptr->next;
}else{
more_ptr->next = head;
more_ptr = more_ptr->next;
}
head = head->next;
}
//连接两个指针。
less_ptr->next = more_head.next;
more_ptr->next = NULL;

return less_head.next;
}
};
思路:

用双指针。
创建两个头结点。比x小的划到第一个里面,否则划到第二个里面,最后将两个链表链接返回。