題目
給定一個鏈表和一個特定值 x,對鏈表進行分隔,使得所有小於 x 的節點都在大於或等於 x 的節點之前。
你應當保留兩個分區中每個節點的初始相對位置。
示例:
輸入: head = 1->4->3->2->5->2, x = 3
輸出: 1->2->2->4->3->5
方案:單鏈表
struct ListNode* partition(struct ListNode* head, int x){
struct ListNode *small = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode *big = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* pSmall = small;
struct ListNode* pBig = big;
while(head){
if(head->val<x){
pSmall->next = head;
pSmall = pSmall->next;
}else {
pBig->next = head;
pBig = pBig->next;
}
head = head->next;
}
pBig->next = NULL;
pSmall->next = big->next;
return small->next;
}
複雜度計算