-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path21.cpp
More file actions
81 lines (78 loc) · 1.13 KB
/
21.cpp
File metadata and controls
81 lines (78 loc) · 1.13 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include<iostream>
#include<cstdio>
#include<cmath>
#include<string>
#include<cstring>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1!=NULL&&l2!=NULL)
{
ListNode *p=l1;
ListNode *q=l2;
ListNode *t,*h;//t新链表,h头指针
//初始表
if(p->val>q->val)
{
t=q;
h=q;
q=q->next;
}
else{
t=p;h=p;
p=p->next;
}
while(p!=NULL&&q!=NULL)
{
if(p->val>q->val)
{
t->next=q;
t=t->next;//都是改后挪
q=q->next;
}
else
{
t->next=p;
t=t->next;
p=p->next;
}
}
while(p!=NULL&&q==NULL)
{
t->next=p;
p=p->next;
t=t->next;
}
while(p==NULL&&q!=NULL)
{
t->next=q;
q=q->next;
t=t->next;
}
while(p==NULL&&q==NULL)
{
return h;
}
}
if(l1==NULL&&l2!=NULL)
{
return l2;
}
if(l1!=NULL&&l2==NULL)
{
return l1;
}
if(l1==NULL&&l2==NULL)
return NULL;
}
};