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.

题意

融合两个已经排好序的链表,并返回一个新表。

思路

先找到表头,然后做个循环不断排序下去即可。

代码

C语言版本:

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
40
41
42
43
44
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* (struct ListNode* l1, struct ListNode* l2) {
if (l1 == NULL){
return l2;
}
if (l2 == NULL){
return l1;
}
struct ListNode* head = NULL;
// find the first element
if (l1->val < l2->val){
head = l1;
l1 = l1->next;
}else{
head = l2;
l2 = l2->next;
}
struct ListNode* p = head;
while(l1&&l2){
if (l1->val < l2->val){
p->next = l1;
l1 = l1->next;
}else{
p->next = l2;
l2 = l2->next;
}
p = p->next;
}
if(l1){
p->next=l1;
}else{
p->next=l2;
}
return head;
}

结果:
208 / 208 test cases passed.
Status: Accepted
Runtime: 4 ms