首页 > 代码库 > [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.
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 ListNode *dummy = new ListNode(0);13 ListNode *ret = NULL;14 15 16 ListNode *p1 = l1;17 ListNode *p2 = l2;18 19 ListNode *p = dummy;20 21 while(p1 && p2){22 if (p1->val < p2->val){23 p->next = p1;24 p1 = p1->next;25 }else{26 p->next = p2;27 p2 = p2->next;28 }29 p = p->next;30 }31 32 p1 = (!p1) ? p2 : p1;33 34 while (p1){35 p->next = p1;36 // don‘t forget to move p1 !!37 p1 = p1->next;38 p = p->next;39 }40 41 ret = dummy->next;42 delete dummy;43 return ret;44 }45 };
[LeetCode] 21. Merge Two Sorted Lists
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。