You are viewing a single comment's thread. Return to all comments →
Not very clean, but non-recursive solution that uses given class in js:
function mergeLists(head1, head2) { if(head1 === null) return head2; if(head2 === null) return head1; let returnNode; if(head1.data < head2.data){ returnNode = new SinglyLinkedListNode(head1.data); head1 = head1.next; }else { returnNode = new SinglyLinkedListNode(head2.data); head2 = head2.next } let currentNode = new SinglyLinkedListNode(); returnNode.next = currentNode; while(head1 != null && head2 != null){ if(head1.data <= head2.data){ currentNode.data = head1.data; head1 = head1.next; currentNode.next = new SinglyLinkedListNode(); currentNode = currentNode.next; }else if(head1.data > head2.data){ currentNode.data = head2.data; head2 = head2.next; currentNode.next = new SinglyLinkedListNode(); currentNode = currentNode.next; } } if(head1 === null && head2 != null){ currentNode.data = head2.data; currentNode.next = head2.next; }; if(head2 === null && head1 != null){ currentNode.data = head1.data; currentNode.next = head1.next; }; return returnNode; }
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 →
Not very clean, but non-recursive solution that uses given class in js: