86. 分隔連結串列
阿新 • • 發佈:2021-01-04
給你一個連結串列和一個特定值 x
,請你對連結串列進行分隔,使得所有小於 x
的節點都出現在大於或等於 x
的節點之前。
- 你應當保留兩個分割槽中每個節點的初始相對位置。
示例:
輸入:head = 1->4->3->2->5->2, x = 3
輸出:1->2->2->4->3->5
解答
使用兩個兩邊分別儲存大於和小於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) {
ListNode *dummy1 = new ListNode(0);
ListNode *dummy2 = new ListNode(0);
ListNode *cur1 = dummy1;
ListNode *cur2 = dummy2;
while(head != nullptr){
if(head->val < x){
cur1- >next = head;
head = head->next;
cur1 = cur1->next;
cur1->next = nullptr;
}
else{
cur2->next = head;
head = head->next;
cur2 = cur2->next;
cur2- >next = nullptr;
}
}
cur1->next = dummy2->next;
return dummy1->next;
}
};