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 .
Problem Solving Ideas:
One:
The table is traversed with two pointers, where the P pointer is used to find points less than X, and the pre is used to manage the linked list, which mainly investigates the basic operation of the linked list;
1. Creating a head node
2. Find the
Once found, move the node to the Pre->next;pre to move backward one step;
3. Continue to find
Two:
Create two linked lists a storage element that is less than x, an element that stores more than X, and the end of a small linked list that joins a large list
Code Listing 1:
/** 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* e=NewListNode (0); E->next=Head; ListNode* pre=e; ListNode* p=e; ListNode*Pnext; while(p!=NULL) { while(p->next!=null&&p->next->val>=x) P=p->Next; if(P->next==pre->next)//not moved, found less than element, Pre=pre->next{p=p->Next; Pre=pre->Next; } Else //moved, found less than element or found empty { if(p->next==NULL) { returnE->Next; } Else{Pnext=p->Next; P->next=pnext->Next; Pnext->next=pre->Next; Pre->next=Pnext; Pre=pre->Next; P=Pre; } } } returnE->Next; }};
Code Listing 2:
/** 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* e1=NewListNode (0); ListNode* e2=NewListNode (0); ListNode* pre1=E1; ListNode* pre2=E2; ListNode* p=Head; while(p!=NULL) { if(p->val<x) {Pre1->next=p; P=p->Next; Pre1=pre1->Next; Pre1->next=NULL; } Else{Pre2->next=p; P=p->Next; Pre2=pre2->Next; Pre2->next=NULL; }} pre1->next=e2->Next; returnE1->Next; }};
[Leetcode] Partition List