Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given
return
------------------------ codes -------------------------------Given
1->4->3->2->5->2
and x = 3,return
1->2->2->4->3->5
/**
* 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 == NULL || head->next == NULL) {
return head;
}
ListNode **cur = &head;
ListNode fakeHead(-1);
ListNode *cur2 = &fakeHead;
while(*cur) {
if ((*cur)->val < x) {
cur = &((*cur)->next);
} else {
ListNode *tmp = *cur;
*cur = tmp->next;
cur2->next = tmp;
cur2 = tmp;
//bug here
//when we insert one node from another list, we should always cut the previous list ahead by setting tmp->next = NULL
tmp->next = NULL;
}
}
if (head == NULL) {
head = fakeHead.next;
} else {
*cur = fakeHead.next;
}
return head;
}
};
---------------------------------------- faster codes ------------------------------------
/**
* 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 == NULL || head->next == NULL) {
return head;
}
ListNode shead(-1);
ListNode bhead(-1);
ListNode *scur = &shead;
ListNode *bcur = &bhead;
ListNode *cur = head;
ListNode *nxt;
while(cur) {
nxt = cur->next;
if (cur->val < x) {
cur->next = NULL;
scur->next = cur;
scur = cur;
} else {
cur->next = NULL;
bcur->next = cur;
bcur = cur;
}
cur = nxt;
}
if (shead.next == NULL) {
return bhead.next;
} else {
scur->next = bhead.next;
return shead.next;
}
}
};
No comments:
Post a Comment