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 1->4->3->2->5->2
and x = 3,
return 1->2->2->4->3->5
.
Subscribe to see which companies asked this question
【解題思路】
題意:
給定一個單鏈表和一個x,把鏈表中小於x的節點放到前面,
大於等於x的節點放到後面,每部分元素的原始相對位置不變。
思路:
其實很簡單,遍歷一遍鏈表,把小於x節點的都掛到small後,
把大於等於x的都放到big後面後,
最後再把大於等於的鏈表big掛到小於鏈表的後面就可以了。
【代碼實現】
struct ListNode* partition(struct ListNode* head, int x)
{
/*1.異常處理*/
if(!head || !head->next)
return head;
struct ListNode *big = (struct ListNode *)malloc(sizeof(struct ListNode));
struct ListNode *small = (struct ListNode *)malloc(sizeof(struct ListNode));
struct ListNode *b = big;
struct ListNode *s = small;
b->next = NULL;
s->next = NULL;
struct ListNode *p = head;
struct ListNode *pnext = NULL;
while (head) {
pnext = head->next; //保存節點非常重要
/*大於x的節點掛在x的後面,即掛在b的後面即可*/
if(head->val >= x) {
b->next = head;
b = b->next;
b->next = NULL;
/*小於x的節點掛在x的後面,小的掛在s的後面即可*/
} else {
s->next = head;
s = s->next;
s->next = NULL;
}
head = pnext;
}
s->next = big->next;/*大的結點掛在小的節點後面*/
head = small->next;/*小的頭結點*/
free(small);
free(big);
return head;
}