1
|
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
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
45
46
47
|
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct
ListNode* mergeTwoLists(
struct
ListNode* l1,
struct
ListNode* l2) {
//首先判断有没有空链表的情况。。。。。
if
(l1 && !l2)
return
l1;
if
(!l1 && l2)
return
l2;
if
(!l1 && !l2)
return
NULL;
//还是和之前的002题要保存新链表头,中间节点head负责遍历
struct
ListNode* head;
struct
ListNode* ret;
//找到新链表的头
if
(l1->val<l2->val){
head=l1;
l1=l1->next;
}
else
{
head=l2;
l2=l2->next;
}
ret=head;
//负责遍历。哪个小就指向哪个,直到有一个遍历完
while
(l1&&l2){
if
(l1->val<l2->val){
head->next=l1;
l1=l1->next;
}
else
{
head->next=l2;
l2=l2->next;
}
head=head->next;
}
//遍历完后看看谁还剩下直接指向剩下的部分
if
(l1){
head->next=l1;
}
if
(l2){
head->next=l2;
}
return
ret;
}
|
。。。。。。。。。。。。。。。。太笨了。。。。。。。。。。。。。。。。继续练习吧少年。。。。。。。。。。。。。。。
本文转自 努力的C 51CTO博客,原文链接:http://blog.51cto.com/fulin0532/1864639