首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。