题目描述:
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 */
递归解决方案:
1 class Solution { 2 public: 3 ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { 4 5 if(l1 == nullptr) 6 return l2; 7 if(l2 == nullptr) 8 return l1; 9 if(l1->val <= l2->val) 10 { 11 l1->next = mergeTwoLists(l1->next,l2); 12 return l1; 13 } 14 else 15 { 16 l2->next = mergeTwoLists(l1,l2->next); 17 returnl2; 18 } 19 20 } 21 };
非递归不使用辅助头结点方案:
1 class Solution { 2 public: 3 ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { 4 5 if(l1 == nullptr) 6 return l2; 7 if(l2 == nullptr) 8 return l1; 9 10 ListNode *head = nullptr; 11 ListNode *p1 = l1; 12 ListNode *p2 = l2; 13 ListNode *last = nullptr; 14 while(p1!=nullptr && p2!=nullptr) 15 { 16 if(p1->val <= p2->val) 17 { 18 if(head == nullptr) 19 { 20 head = p1; 21 last = head; 22 } 23 else 24 { 25 last->next = p1; 26 last = p1; 27 } 28 29 p1 = p1->next; 30 } 31 else 32 { 33 if(head == nullptr) 34 { 35 head = p2; 36 last = head; 37 } 38 else 39 { 40 last->next = p2; 41 last = p2; 42 } 43 44 p2 = p2->next; 45 } 46 } 47 48 if (p1 != nullptr) 49 last->next = p1; 50 if (p2 != nullptr) 51 last->next = p2; 52 53 return head; 54 55 } 56 };
非递归使用辅助头结点方案:
1 class Solution { 2 public: 3 ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { 4 5 if(l1 == nullptr) 6 return l2; 7 if(l2 == nullptr) 8 return l1; 9 10 ListNode *dummy = new ListNode(-1); 11 ListNode *p1 = l1; 12 ListNode *p2 = l2; 13 ListNode *last = dummy; 14 while(p1!=nullptr && p2!=nullptr) 15 { 16 if(p1->val <= p2->val) 17 { 18 last->next = p1; 19 last = p1; 20 p1 = p1->next; 21 } 22 else 23 { 24 last->next = p2; 25 last = p2; 26 p2 = p2->next; 27 } 28 } 29 30 if (p1 != nullptr) 31 last->next = p1; 32 if (p2 != nullptr) 33 last->next = p2; 34 35 ListNode *ret = dummy->next; 36 dummy->next = nullptr; 37 delete dummy; 38 39 return ret; 40 41 } 42 };