LeetCode 86. 分隔链表
题目
给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
示例:
输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5
分析
用两个新链表分别存贮大于等于x的值和小于x的值,然后再将两个链表拼起来即可。
C++代码
/**
* 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* t1_head = new ListNode(0);
ListNode* t1_end = t1_head;
ListNode* t2_head = new ListNode(0);
ListNode* t2_end = t2_head;
while(head != NULL){
if(head->val < x){
t1_end->next = new ListNode(head->val);
t1_end = t1_end->next;
}else{
t2_end->next = new ListNode(head->val);
t2_end = t2_end->next;
}
head = head->next;
}
t1_end->next = t2_head->next;
return t1_head->next;
}
};