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 .
Title Requirements:
For a linked list and a numeric x, place all nodes that are less than X in front of all nodes that are greater than or equal to X.
Requires that the relative order of the original linked table nodes not be changed.
Problem Solving Ideas:
In the array partition, it is usually through the first and the two pointers to the front and back traversal and exchange;
In the list, you do not need to exchange elements, you can create two new head node pointers, to point to the nodes less than x and the nodes greater than or equal to X, after the end of the traversal, and then reconnect the two new linked list.
Code:
/** 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) {ListNode*left_head=null,*left_tail=NULL; ListNode*right_head=null,*right_tail=NULL; ListNode*p=Head; while(p) {if(p->val<x) { if(left_tail) {Left_tail->next=p; Left_tail=left_tail->Next; } ElseLeft_head=left_tail=p; } Else{ if(right_tail) {Right_tail->next=p; Right_tail=right_tail->Next; } ElseRight_head=right_tail=p; } P=p->Next; } if(right_tail) Right_tail->next=NULL; if(left_tail) Left_tail->next=Right_head; returnLeft_head?Left_head:right_head; }};
(Leetcode) Partition List