forked from leetcoders/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMergeTwoSortedLists.h
39 lines (36 loc) · 966 Bytes
/
MergeTwoSortedLists.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/*
Author: Annie Kim, [email protected]
Date: Apr 17, 2013
Update: Sep 2, 2013
Problem: Merge Two Sorted Lists
Difficulty: Easy
Source: http://leetcode.com/onlinejudge#question_21
Notes:
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.
Solution: ...
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
ListNode head(0), *cur = &head;
while (l1 && l2)
{
ListNode **min = l1->val < l2->val ? &l1 : &l2;
cur->next = *min;
cur = cur->next;
*min = (*min)->next;
}
if (l1) cur->next = l1;
if (l2) cur->next = l2;
return head.next;
}
};