86. 分隔链表
给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
解题思路: 在遍历链表的过程中,可以将小于x的节点放在一个链表上,将大于或等于x的节点放在另一个链表上,然后将这两个链表拼起来即可。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
if (!head) return NULL;
ListNode *l = new ListNode(-1), *p = l, *g = new ListNode(0), *q = g;
ListNode *dummy = new ListNode(-1), *cur = dummy;
dummy->next = head;
while (cur->next) {
ListNode *t = cur->next;
if (cur->next->val < x) {
cur->next = cur->next->next;
p->next = t;
p = t;
t->next = NULL;
} else {
cur->next = cur->next->next;
q->next = t;
q = t;
t->next = NULL;
}
}
p->next = g->next;
head = l->next;
delete dummy;
delete l;
delete g;
return head;
}
};