"086-partition list (to partition a single linked list)""leetcode-Interview algorithm classic-java Implementation" "All topics Directory Index"Original Question
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater 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 x = 3 and,
Return 1->2->2->4->3->5 .
Main Topic
Given a single-linked list and a value x, the list is divided into parts that are less than or equal to x and greater than X. At the same time, keep the list of the original relative order.
Thinking of solving problems
Create two linked lists A, B, place each node in the original linked list, less than or equal to X, at the end of the A-linked list, if it is greater than the end of B., and finally the head node of B to the end of a.
Code Implementation
Node class
publicclass ListNode { int val; ListNode next; ListNode(int x) { val = x; }}
Algorithm implementation class
Public classSolution { PublicListNodePartition(ListNode Head,intx) {ListNode Le =NewListNode (0);//Less than x linked listListNode GE =NewListNode (0);linked list with//greater than or equal to xListNode T1 = le; ListNode t2 = GE; ListNode p = head; while(P! =NULL) {if(P.val < X) {t1.next = p; T1 = p; }Else{t2.next = p; t2 = p; } p = P.next; } T2.next =NULL;//Indicates that there is data on the linked list less than if(T1! = le) {t1.next = Ge.next; head = Le.next; }Else{head = Ge.next; }returnHead }}
Evaluation Results
Click on the picture, the mouse does not release, drag a position, release after the new window to view the full picture.
Special InstructionsWelcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/47290703"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Leetcode-Interview algorithm classic-java implementation" "086-partition list (to partition a single linked list)"