Reprint Please specify source: Http://www.cnblogs.com/gufeiyang
Personal micro-Blog: flysea_gu
Test instructions
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.
Train of thought: Two order list merge, nothing to say, the only thing to say, ptr pointer do not forget to move
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode* Mergetwolists (listnode* L1, listnode*L2) { if(L1 = = NULL)returnL2; if(L2 = = NULL)returnL1; ListNode*root =NewListNode (0); ListNode* ptr =Root; while(L1!=null && l2!=NULL) { if(L1->val <= l2->val) {ptr->next =L1; L1= l1->Next; } Else{ptr->next =L2; L2= l2->Next; } ptr= ptr->Next; } while(L1) {ptr->next =L1; L1= l1->Next; PTR= ptr->Next; } while(L2) {ptr->next =L2; L2= l2->Next; PTR= ptr->Next; } ptr= root->Next; DeleteRoot; returnptr; }};
View Code
Leetcode 21. Merge Sorted Lists