One Day together Leetcode
This series of articles has all been uploaded to my github address: Zeecoder ' s GitHub
You are welcome to follow my Sina Weibo, my Sina Weibo blog
Welcome reprint, Reprint please indicate the source
(i) Title
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or >equa l 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.
(ii) Problem solving
Topic: Given a list and a value, the nodes smaller than the given value are moved to the front of the list, but cannot change the relative position of the numbers in the original linked list.
The idea of solving a problem: with two pointers, one to the end of the linked list portion less than the given value, one for traversing the linked list.
/** * 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* lesstail = head;//Less than x part of tail nodelistnode* p = head; listnode* pre = NULL;//p nodes in front of BOOLIsFirst =false;//If the head node is greater than X is true, and vice versa false BOOLNeedtochange =false;//p in front of the nodes are less than x, you do not need to change, and the need to insert operations if(Head->val >= x) {IsFirst =true; Needtochange =true;}//If the first number is greater than X, the head node needs to be changed while(P!=null) {if(P->val < X) {if(IsFirst)//need to change head node{listnode* temp = p->next; Pre->next = p->next; p->next=head; Lesstail = p; head = p; p = temp; IsFirst =false; }Else{if(!needtochange)///Front part is less than x, no change required{lesstail = p; Pre = P; p=p->next; }Else//insert operation required{listnode* temp = p->next; Pre->next = p->next; P->next = lesstail->next; Lesstail->next = p; Lesstail = p;//Note To change the tail node less than the X partp = temp; } } }Else{pre = P; p=p->next; Needtochange =true; } }returnHead }};
PostScript: Here I wish you a Happy Dragon Boat festival, but also to the Dragon Boat Festival is still sticking to brush the question of my own point of praise. Ha ha!
"One Day together Leetcode" #86. Partition List