【LeetCode】021. Merge Two Sorted Lists
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.
Example:
Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4
题解:
简单的链表遍历,还可用递归做。
Solution 1
1 v/** 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 ListNode dummy(-1); 13 ListNode* cur = &dummy; 14 15 while(l1 && l2) { 16 if (l1->val < l2->val) { 17 cur->next = l1; 18 l1 = l1->next; 19 } else { 20 cur->next = l2; 21 l2 = l2->next; 22 } 23 cur = cur->next; 24 } 25 26 cur->next = l1 ? l1 : l2; 27 28 return dummy.next; 29 } 30 };
递归方法
Solution 2
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 15 if (l1->val < l2->val) { 16 l1->next = mergeTwoLists(l1->next, l2); 17 return l1; 18 } else { 19 l2->next = mergeTwoLists(l1, l2->next); 20 return l2; 21 } 22 } 23 };