Given a linked list and a value x, partition it such that all nodes less than x come before nodes greate R than or equal to x.
You should preserve the original relative order of the nodes in each of the.
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
Solution 1: From the beginning, find the first value greater than or equal to the X node, and then find the first node after the node is less than X, and finally the small node inserted in front of the large node, and then move to the first large node in the previous step, continue to loop the previous processing, until there is no value less than x node.
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode* Partition (listnode* head,intx) {if(head = = NULL | | head->next = = NULL)returnHead; ListNode*help =NewListNode (0); Help->next =Head; ListNode* prev = help, *curr = prev->Next; while(Curr! =NULL) { while(Curr! = NULL && Curr->val < x) {//find the first node greater than or equal to xCurr = curr->Next; Prev= prev->Next; } if(Curr = = NULL) Break; ListNode*next = curr->next, *temp = Curr;//note not starting with the first node while(Next! = NULL && next->val >= x) {//find the first node less than xNext = next->Next; Temp= temp->Next; } if(Next = NULL) Break; ListNode* tmp = next->Next; Next->next = prev->next;//insert nodes that are less than x before nodes greater than or equal to xPrev->next =Next; Temp->next =tmp; Prev= Next;//move forward to the next nodeCurr = prev->Next; } returnHelp->Next; }};
Actually the first while loop in the outer while loop can get out of the outer while loop, because the first node that is found next to the value greater than or equal to X is Curr itself.
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode* Partition (listnode* head,intx) {if(head = = NULL | | head->next = = NULL)returnHead; ListNode*help =NewListNode (0); Help->next =Head; ListNode* prev =Help ; while(Prev->next! = NULL && prev->next->val < x) prev = prev->Next; ListNode* Curr =prev; while(Curr->next! =NULL) { if(Curr->next! = NULL && curr->next->val >=x) Curr= curr->Next; Else{ListNode* tmp = curr->Next; Curr->next = tmp->Next; TMP->next = prev->Next; Prev->next =tmp; Prev= prev->Next; } } returnHelp->Next; }};
Solution 2: Another way is to iterate through the linked list, respectively, the value is less than x and the value is greater than or equal to the X node is divided into two chain links, and then link the latter at the end of the former.
[Leetcode]89. Partition List Chain List division