You are viewing a single comment's thread. Return to all comments →
Solution in C++:
SinglyLinkedListNode* mergeLists(SinglyLinkedListNode* head1, SinglyLinkedListNode* head2) { SinglyLinkedListNode* head = NULL; if(head1 == NULL) return head2; else if(head2 == NULL) return head1; else { if(head1->data <= head2->data) { head = head1; head1 = head1->next; } else { head = head2; head2 = head2->next; } SinglyLinkedListNode* ptr; ptr = head; while(head1 != NULL || head2 != NULL) { if(head1 != NULL && head2 != NULL) { if(head1->data <= head2->data) { ptr->next = head1; head1 = head1->next; } else { ptr->next = head2; head2 = head2->next; } } else if(head1 != NULL) { ptr->next = head1; head1 = head1->next; } else if(head2 != NULL) { ptr->next = head2; head2 = head2->next; } ptr = ptr->next; } } return head; }
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 in C++: