給定一個鏈表和一個特定值 x,對鏈表進行分隔,使得所有小于 x 的節點都在大于或等于 x 的節點之前。
你應當保留兩個分區中每個節點的初始相對位置。
示例:
輸入: head = 1->4->3->2->5->2, x = 3
輸出: 1->2->2->4->3->5來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/partition-list
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
解法:
/*** 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 head;ListNode* dumy = new ListNode(0), *p = dumy;dumy->next = head;ListNode *dumy2 = new ListNode(0), *curr = dumy2;while(p->next){if(p->next->val >= x){curr->next = p->next;curr = p->next;p->next = p->next->next;}else{p = p->next;}}curr->next = NULL;p->next = dumy2->next;return dumy->next;}
};
?