. Merge Sorted Lists
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.
The main idea: merging two orderly linked lists
Idea: By comparing the node size of two linked lists, the tail interpolation method is used to establish the linked list.
The code is as follows:
/** * definition for singly-linked list. * struct listnode { * int val; * ListNode *next; * listnode (int x) : val (x), next (NULL) {} * }; */class solution {public: listnode* mergetwolists (ListNode *&NBSP;L1,&NBSP;LISTNODE*&NBSP;L2) { ListNode * newlisthead,* newlistnode,*newlisttail; newlisthead = (listnode *) malloc (sizeof (ListNode)); newlisttail = newListHead; &nBsp; while ( (NULL&NBSP;!=&NBSP;L1) && (NULL&NBSP;!=&NBSP;L2) ) { if (L1->val <= l2->val) { newListNode = (listnode *) malloc (sizeof (ListNode)); newListNode->val = l1->val; newlisttail->next = newListNode; newListTail = newListNode; l1 = l1->next; } else { newListNode = (listnode *) malloc (sizeof (ListNode)); newlistnode->val = l2->val; newListTail->next = newListNode; newListTail = newListNode; l2 = l2->next; } } if (NULL&NBSP;!=&NBSP;L1) { while ( L1) { newListNode = (listnode *) malloc (sizeof (ListNode)); newListNode->val = l1->val; newListTail->next = newListNode; newListTail = newlistnode; l1 = l1->next; } } if (NULL &NBSP;!=&NBSP;L2) { while (L2) { newlistnode = (listnode *) malloc (sizeof (ListNode)); newListNode->val = l2->val; newListTail->next = newlistnode; newlisttail = Newlistnode; l2 = l2->next; } } newlisttail->next = NULL; return newListHead->next; }};
2016-08-06 01:40:31
This article is from the "Do Your best" blog, so be sure to keep this source http://qiaopeng688.blog.51cto.com/3572484/1834921
Leetcode 21. Merge Sorted Lists consolidated linked list