首页 > 代码库 > leetcode 21.Merge Two Sorted Lists

leetcode 21.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.

为了方便表头处理,对l1添加dummy头节点,并把l2上的节点插入l1中。

 1 ListNode *mergeTwoLists(ListNode *l1, ListNode *l2)  2     { 3         ListNode *dummy = new ListNode(INT_MIN), *p, *r; 4         dummy->next = l1; 5          6         p = dummy; 7         while (l2 != NULL && p->next != NULL) 8         { 9             if (l2->val < p->next->val)10             {11                 r = l2;12                 l2 = r->next;13                 r->next = p->next;14                 p->next = r;15             }16             p = p->next;17         }18         if (l2 != NULL)19             p->next = l2;20         p = dummy->next;21         delete dummy;22         23         return p;24     }

 

leetcode 21.Merge Two Sorted Lists