86. 分隔链表
给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
示例 :
输入: head = 1->4->3->2->5->2, x = 3.
输出:1->2->2->4->3->5.
解决这道题的思路:
维护两个链表 big 和 small,遍历链表,大于等于 x 的结点接在 big 后,小于 x 的接在 small 后。最后连接两个链表,返回 small 链表的头即可。
/**
* 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) {
ListNode* big = new ListNode(0), *small = new ListNode(0);
auto p = big, q = small;
while (head != nullptr) {
if (head->val >= x) {
auto n = new ListNode(head->val);
p->next = n;
p = p->next;
}
else {
auto n = new ListNode(head->val);
q->next = n;
q = q->next;
}
head = head->next;
}
q->next = big->next;
return small->next;
}
};