Topic:
Chain List Division
Given a single-linked list and a numeric x, the list is divided so that all nodes less than x are ranked before nodes greater than or equal to X.
You should keep the relative order of the linked list nodes in the two parts.
Sample Example
Given the list 1->4->3->2->5->2->null, and x=3
Back to 1->2->2->4->3->5->null
Solving:
The result of the above return is a lot of wrong should be: 1->2->2->3->4->5->null
Think for a long time do not know how to do, nine chapters to see the program, unexpectedly make two chain links to connect up ...
Java Program:
/*** Definition for ListNode. * public class ListNode {* int val; * ListNode Next; * ListNode (int val) {* This.val = val; * This.next = null; * } * } */ Public classSolution {/** * @paramhead:the first node of linked list. * @paramX:an Integer *@return: a ListNode*/ PublicListNode partition (ListNode head,intx) {//Write your code here if(Head = =NULL)return NULL; ListNode Leftdummy=NewListNode (0); ListNode Rightdummy=NewListNode (0); ListNode Left= Leftdummy, right =Rightdummy; while(Head! =NULL) { if(Head.val <x) {Left.next=Head; Left=Head; } Else{Right.next=Head; Right=Head; } head=Head.next; } Right.next=NULL; Left.next=Rightdummy.next; returnLeftdummy.next; } }
View Code
Total time: 1573 Ms
Python program:
"""Definition of Listnodeclass ListNode (object): Def __init__ (Self, Val, next=none): Self.val = Val Self . Next = Next"""classSolution:"""@param head:the first node of linked list. @param x:an integer @return: a ListNode""" defpartition (self, head, x):#Write your code here ifHead = =None:returnHead Lefthead=listnode (0) Righthead=listnode (0) left=Lefthead Right=Righthead whilehead!=None:ifhead.val<X:left.next=Head Left=Left.nextElse: Right.next=Head Right=Right.next Head=Head.next Right.next=None Left.next=Righthead.nextreturnLefthead.next
View Code
Total time: 517 MS
It's a little bit different from Java, but it has no effect.
Lintcode Easy title: Partition List Link List Division