-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathList_Merge.cpp
More file actions
91 lines (89 loc) · 1.09 KB
/
List_Merge.cpp
File metadata and controls
91 lines (89 loc) · 1.09 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
82
83
84
85
86
87
88
89
90
91
#include <iostream>
using namespace std;
typedef struct node
{
int data;
struct node* next;
}List,*pList;
pList createList()
{
pList head,p,q;
head=new List;
head=NULL;
int num;
cin>>num;
while(num!=-1)
{
p=new List;
p->data=num;
p->next=NULL;
if(head==NULL)
{
head=p;
q=head;
}
else
{
q->next=p;
q=p;
}
cin>>num;
}
return head;
}
void Print(pList head)
{
pList p=head;
while(p)
{
if(p->next==NULL)
cout<<p->data;
else
cout<<p->data<<" -> ";
p=p->next;
}
cout<<endl;
}
pList Merge(pList head1, pList head2)
{
if(head1==NULL && head2==NULL)
return NULL;
if(head1==NULL&&head2)
return head2;
if(head1 && head2==NULL)
return head1;
pList p,q,pre,tmp;
pre=NULL;
p=head1;
q=head2;
while(p && q)
{
if(p->data<q->data)
{
pre=p;
p=p->next;
}
else
{
tmp=q;
q=q->next;
tmp->next=p;
pre->next=tmp;
pre=tmp;
}
}
if(q)
pre->next=q;
return head1;
}
int main()
{
pList head1,head2;
head1=new List;
head2=new List;
head1=createList();
head2=createList();
Merge(head1,head2);
Print(head1);
return 0;
}