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(-1);
13: ListNode *cur = dummy;
14: while (l1 && l2) {
15: if (l1->val < l2->val) { cur->next = l1; l1 = l1->next; }
16: else { cur->next = l2; l2 = l2->next; }
17: cur = cur->next;
18: }
19: if (l1) cur->next = l1;
20: if (l2) cur->next = l2;
21: cur = dummy->next;
22: delete dummy;
23: return cur;
24: }
25: };
Saturday, August 6, 2016
21. Merge Two Sorted Lists
Well, this is a real easy one.
Labels:
amazon,
leetcode,
linked list,
merge list
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment