Datastructures-链表

还记得他怎么说?“更重要的是,知道如何调整这样一种结构”

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
#include<bits/stdc++.h>
using namespace std;

typedef int ElementType;
typedef struct Node *PtrToNode;
struct Node{
ElementType Data;
PtrToNode Next;
};
typedef PtrToNode List ;

List Read();
void Print(List L);
List Merge(List L1,List L2);

int main()
{
List L1,L2,L;
L1 = Read();
L2 = Read();
Print(L1);
Print(L2);
L = Merge(L1,L2);
Print(L);
Print(L1);
Print(L2);
return 0;
}
List Read()
{
List L = (List)malloc(sizeof(struct Node));
List head = L;
int n;cin >> n;
for(int i = 1;i <= n;++ i)
{
int data;
scanf("%d",&data);
List X = (List)malloc(sizeof(struct Node));
X->Data = data;
L->Next = X;
L = L->Next;
}
L->Next = NULL;
return head;
}
void Print(List L)
{
List t = L->Next;
if(t==NULL)
{
printf("NULL");
}
for(;t;t=t->Next)
{
printf("%d ",t->Data);
}
printf("\n");
// if(L->Next = NULL)
// {
// printf("NULL");
// }
// while(L->Next!=NULL)
// {
// printf("%d",L->Next->Data);
// L = L->Next;
// }
}
List Merge(List L1,List L2)
{
List L = (List)malloc(sizeof(struct Node));
List head = L;
List tmpL1 = L1->Next;
List tmpL2 = L2->Next;
while(tmpL1 && tmpL2)
{
if(tmpL1->Data < tmpL2->Data){
L->Next = tmpL1;
tmpL1 = tmpL1->Next;
}else{
L->Next = tmpL2;
tmpL2 = tmpL2->Next;
}
L = L->Next;
}
if(tmpL1)
{
L->Next = tmpL1;
}
if(tmpL2)
{
L->Next = tmpL2;
}
L1->Next = NULL;
L2->Next = NULL;
return head;
}
//为什么像注释中那样写就无法输出?
//为什么要专门留一个head结点(哑结点)不存数据?
//如何理解这个合并过程?重组or复制?

Datastructures-链表
https://43.242.201.154/2024/09/07/Datastructures-链表/
Author
Dong
Posted on
September 7, 2024
Licensed under