ListNode Class (Node Class)
1 Packageleetcode.utilities;2 3 Public classListNode {4 Public intVal;5 PublicListNode Next;6 PublicListNode (intval) {7 //TODO auto-generated Constructor stub8 This. val =Val;9 This. Next =NULL ; Ten } One //Print linked list A Public Static voidprintlist (ListNode head) { -System.out.println ("Prinylist start"); -ListNode Pnode =head; theSystem.out.print ("{"); - while(Pnode! =NULL){ -System.out.print (Pnode.val + ""); -Pnode=Pnode.next; + } -System.out.println ("}"); + } A}
Implement Java code recursively:
1 PackageCom.hb.jzoffer;2 3 ImportLeetcode.utilities.ListNode;4 //question 17: Merging two sorted lists5 Public classmergesortedlists {6 Publiclistnode Merge (ListNode pHead1, ListNode pHead2) {7 //determine if two linked lists are empty8 if(PHead1 = =NULL ){9 returnpHead2;Ten}Else if(PHead2 = =NULL ){ One returnPHead1; A } - -ListNode Pmergedhead =NULL; the - //Recursive invocation - if(Phead1.val <phead2.val) { -Pmergedhead =PHead1; + //The following recursive call itself, the returned value is Pmergedhead after the node, until the end of recursion, will return Pmergedhead new head node. -Pmergedhead.next =merge (Phead1.next, pHead2); +}Else{ APmergedhead =pHead2; atPmergedhead.next =merge (PHead1, phead2.next); - } - - returnPmergedhead; - } - in Public Static voidMain (string[] args) { -ListNode Head1 =NewListNode (1); toListNode N1 =NewListNode (3); +ListNode N2 =NewListNode (5); -ListNode n3 =NewListNode (7); theListNode N4 =NewListNode (9); * $Head1.next =N1;Panax NotoginsengN1.next =N2; -N2.next =N3; theN3.next =N4; + AListNode head2 =NewListNode (2); theListNode N5 =NewListNode (4); +ListNode N6 =NewListNode (6); - $Head2.next =N5; $N5.next =N6; - -Mergesortedlists merge =Newmergesortedlists (); the -ListNode Mergehead =Merge.merge (Head1, head2);Wuyi the listnode.printlist (Mergehead); - Wu } -}
Interview question 17: Merge two sorted lists