Leetcode 21. Merge Two Sorted Lists
21. Merge Two Sorted Lists
- Total Accepted: 138746
- Total Submissions: 383218
- Difficulty: Easy
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
思路:递归或者迭代添加节点。
代码:
递归:
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 class Solution { 10 public: 11 ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { 12 if(!l1) return l2; 13 if(!l2) return l1; 14 if(l1->val<l2->val){ 15 l1->next=mergeTwoLists(l1->next,l2); 16 return l1; 17 } 18 l2->next=mergeTwoLists(l1,l2->next); 19 return l2; 20 } 21 };
迭代:
1 class Solution { 2 public: 3 ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { 4 ListNode* head=new ListNode(-1); 5 ListNode* end=head; 6 while(l1&&l2){ 7 if(l1->val<l2->val){ 8 end->next=l1; 9 l1=l1->next; 10 } 11 else{ 12 end->next=l2; 13 l2=l2->next; 14 } 15 end=end->next; 16 } 17 if(l1){ 18 end->next=l1; 19 } 20 else{ 21 end->next=l2; 22 } 23 return head->next; 24 } 25 };