Merge Sorted ListsTotal accepted:61585 Total submissions:188253my submissions QuestionSolution
Merge sorted linked lists and return it as a new list. The new list should is made by splicing together the nodes of the first of the lists.
Hide TagsLinked ListHas you met this question in a real interview? Yes No
discuss
#include <iostream>using namespace std;struct listnode {int val; ListNode *next; ListNode (int x): Val (x), Next (NULL) {}}; listnode* mergetwolists (listnode* L1, listnode* L2) {if (l1==null) return l2;if (l2==null) return L1; ListNode *ptr1=l1;//l1,l2 as the remaining list of the new linked lists OH current head node pointer listnode *ptr2=l2;//listnode *temp;//new linked list tail node pointer ListNode *root;// Final head node if (l1->val<l2->val) {temp=l1;root=l1;ptr1=l1->next;ptr2=l2;} Else{temp=l2;root=l2;ptr1=l1;ptr2=l2->next;} while (1) {if (ptr2==null&&ptr1==null) break;if (ptr1==null&&ptr2!=null) {temp->next=ptr2;break;} if (ptr1!=null&&ptr2==null) {temp->next=ptr1;break;} if (ptr1->val<ptr2->val) {temp->next=ptr1;ptr1=ptr1->next;temp=temp->next;} Else{temp->next=ptr2;ptr2=ptr2->next;temp=temp->next;}} return root;} int main () {ListNode *root1=new ListNode (2); ListNode *root2=new ListNode (1); ListNode *ptr=mergetwolists (root1,root2);cout<<ptr->val<< ' <<ptr->next->val<< Endl;}
leetcode_21 question--merge, Sorted Lists (linked list)