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.
Note that the problem requires merging can not create a new node, directly using the original node, relatively simple, the code is as follows:
1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * ListNode *next;6 * ListNode (int x): Val (x), Next (NULL) {}7 * };8 */9 classSolution {Ten Public: Onelistnode* mergetwolists (listnode* L1, listnode*L2) { A if(L1 = = NULL)returnL2; - if(L2 = = NULL)returnL1; -ListNode * Root =NewListNode (-1); theListNode * Helper =Root; - while(L1!=null && l2!=NULL) { - if(L1->val <= l2->val) -Root->next = L1, l1=l1->Next; + Else if(L1->val > l2->val) -Root->next = L2, l2=l2->Next; +root = root->Next; A } at while(l1!=NULL) { -Root->next =L1; -L1 = l1->Next; -root = root->Next; - } - while(l2!=NULL) { inRoot->next =L2; -L2 = l2->Next; toroot = root->Next; + } - returnHelper->Next; the } *};
Leetcode Oj:merge two Sorted Lists (merge two linked lists)