You are viewing a single comment's thread. Return to all comments →
Solution without recursion
static SinglyLinkedListNode mergeLists(SinglyLinkedListNode head1, SinglyLinkedListNode head2) { if(head1==null) return head2; else if(head2==null) return head1; else if(head1==null && head2==null) return null; else{ SinglyLinkedListNode dummynode=new SinglyLinkedListNode(0); SinglyLinkedListNode tail=dummynode; //1->5->6->9->11 //1->3->4->8-9->10->11->100 SinglyLinkedListNode node1=head1; SinglyLinkedListNode node2=head2; while(node1!=null && node2!=null){ if(node1.data<=node2.data){ SinglyLinkedListNode temp=new SinglyLinkedListNode(node1.data); tail.next=temp; node1=node1.next; } else{ SinglyLinkedListNode temp=new SinglyLinkedListNode(node2.data); tail.next=temp; node2=node2.next; } tail=tail.next; } if(node1!=null){ tail.next=node1; } else{ tail.next=node2; } return dummynode.next; } }
Seems like cookies are disabled on this browser, please enable them to open this website
Merge two sorted linked lists
You are viewing a single comment's thread. Return to all comments →
Solution without recursion