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
.
Test instructions
Given a linked list and a number x, the list partition, less than x is placed in front of greater than or equal to X, and to maintain the relative position of each node within each partition has not changed.
For example, in the original list, 4 in front of 3, 3 in front of 5, after partitioning still maintain this relative position.
Process:
(1) New two linked list, one first, one second,
One is used to record all nodes less than x in the linked list, and one to record all nodes greater than or equal to x in the linked list.
(2) traverse the original linked list.
(3) Finally, the two linked lists are concatenated as the result of the return.
Public classSolution { PublicListNode partition (ListNode head,intx) {if(Head = =NULL)return NULL; ListNode Firstdummy=NewListNode (0); ListNode Seconddummy=NewListNode (0); ListNode First= Firstdummy, second =Seconddummy; while(Head! =NULL){ if(Head.val <x) {First.next=Head; First=Head; }Else{Second.next=Head; Second=Head; } head=Head.next; } First.next=Seconddummy.next; Second.next=NULL; returnFirstdummy.next; }}
Leetcode 86. Partition List