1 struct ListNode { 2 int val; 3 ListNode *next; 4 ListNode(int x) : val(x), next(NULL) {} 5 }; 6 7 class Solution { 8 public: 9 ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { 10 ListNode temp_head(0);//都鏈接到臨時頭節點後面 11 ListNode *ptr = &temp_head; 12 13 while (l1 && l2) { 14 if (l1->val < l2->val) {//小的開始鏈接 15 ptr->next = l1; 16 l1 = l1->next; 17 } else { 18 ptr->next = l2; 19 l2 = l2->next; 20 } 21 ptr = ptr->next; 22 } 23 if (l1) { //若是其中一個有剩餘,l1不小於l2 或者 l2不小於l1 24 ptr->next = l1; 25 } 26 if (l2) { 27 ptr->next = l2; 28 } 29 return temp_head.next;//臨時節點的下一個節點 30 } 31 };
1 int main(int argc, const char * argv[]) { 2 ListNode a(1); 3 ListNode b(2); 4 ListNode c(3); 5 ListNode d(4); 6 ListNode e(5); 7 ListNode f(7); 8 a.next = &b; 9 b.next = &c; 10 d.next = &e; 11 e.next = &f; 12 13 Solution solve; 14 ListNode *head = solve.mergeTwoLists(&a, &d); 15 while (head) { 16 cout <<head->val <<endl; 17 head = head->next; 18 } 19 20 return 0; 21 }