Topic links
Title Requirements:
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 .
The problem can be greatly facilitated by the use of dummy nodes, the specific procedures are as follows:
1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * ListNode *next;6 * ListNode (int x): Val (x), Next (NULL) {}7 * };8 */9 classSolution {Ten Public: Onelistnode* partition (listnode* head,intx) { A if(!head | |!head->next) - returnhead; - theListNode *dummy =NewListNode (int_min); -Dummy->next =head; -ListNode *parnode =dummy; -ListNode *prenode = nullptr, *curnode =nullptr; + while(Parnode && Parnode->val <x) - { +Prenode =Parnode; AParnode = parnode->Next; at } - -Parnode =Prenode; - if(!parnode | |!parnode->next) - { -Head = dummy->Next; in Deletedummy; -dummy =nullptr; to returnhead; + } - thePrenode = parnode->Next; *Curnode = prenode->Next; $ while(Curnode)Panax Notoginseng { - if(Curnode->val <x) the { +ListNode *nextpar = parnode->next, *nextcur = curnode->Next; AParnode->next =Curnode; theCurnode->next =Nextpar; +Parnode = parnode->Next; - $Curnode =nextcur; $Prenode->next =Curnode; - } - Else the { -Prenode = prenode->Next;WuyiCurnode = curnode->Next; the } - } Wu -Head = dummy->Next; About Deletedummy; $dummy =nullptr; - - returnhead; - } A};
Leetcode "Linked list": Partition list