Binary Overflow.

链表的建立排序及其归并

字数统计: 510阅读时长: 3 min
2018/10/17 Share

链表的建立 排序 和非递减归并

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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

struct LinkList
{
int temp;
struct LinkList *next;
};
/**
链表的创建
*/
void CreateLinkList(LinkList *ptr)
{
LinkList *pt = ptr;
cout<<"please input six number:"<<endl;
int index;
int flag = 6;
while(flag--)
{
cin>>index;
LinkList *a = new LinkList;
a->temp = index;
pt->next = a;
pt = a;
}
pt->next = NULL;
LinkList *n = ptr->next;
}
/**
链表的排序
*/
LinkList* SortLinkList(LinkList *ptr)
{
int mid;

LinkList *m = ptr->next;
LinkList *n;
while(m->next!=NULL)
{
n = m->next;
while(n!=NULL)
{
if(n->temp < m->temp)
{
mid = m->temp;
m->temp = n->temp;
n->temp = mid;
}
n = n->next;
}
m = m->next;
}
return ptr;
}
/**
链表的归并
*/
LinkList* MergeLinkList(LinkList *a, LinkList *b)
{
a = a->next;
b = b->next;
LinkList *ptc = new LinkList;
LinkList *ptr = ptc;
while(a!=NULL||b!=NULL)
{
LinkList *c = new LinkList;
if(a==NULL)
{
c->temp = b->temp;
b = b->next;
}
else if(b==NULL)
{
c->temp = a->temp;
a = a->next;
}
else if(a->temp<=b->temp)
{
c->temp = a->temp;
a = a->next;
}
else
{
c->temp = b->temp;
b = b->next;
}
ptr->next = c;
ptr = c;
}
ptr->next = NULL;
return ptc;
}
/**
插入归并
*/
LinkList *TryLinkList(LinkList *a,LinkList *b)
{
LinkList *pta = a->next;
LinkList *ptb = b->next;
LinkList *ptr = b;
while(pta!=NULL)
{
while(ptb!=NULL)
{
if(pta->temp<ptb->temp)
{
LinkList *n = new LinkList;
n->temp = pta->temp;
n->next = ptb;
ptr->next = n;
ptr = n;
break;
}
ptr = ptb;
ptb = ptb->next;
}
if(ptb==NULL && pta!=NULL)
{
ptr->next = pta;
break;
}
else pta = pta->next;
}
cout<<"over!"<<endl;
return b;
}
int main()
{
LinkList *pta = new LinkList;
LinkList *ptb = new LinkList;
CreateLinkList(pta);
CreateLinkList(ptb);
pta = SortLinkList(pta);
ptb = SortLinkList(ptb);
LinkList *p = pta->next;
cout<<"LA:";
while(p!=NULL)
{
cout<<p->temp<<" ";
p = p->next;
}
cout<<endl;
cout<<"LB:";
p = ptb->next;
while(p!=NULL)
{
cout<<p->temp<<" ";
p = p->next;
}
cout<<endl;

//LinkList *ptc = MergeLinkList(pta,ptb);
LinkList *ptc = TryLinkList(pta,ptb);
ptc = ptc->next;
cout<<"LC:";
while(ptc!=NULL)
{
cout<<ptc->temp<<" ";
ptc = ptc->next;
}
free(pta);
free(ptb);
free(ptc);
return 0;
}

CATALOG