-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path4.1.cpp
More file actions
155 lines (139 loc) · 2.53 KB
/
4.1.cpp
File metadata and controls
155 lines (139 loc) · 2.53 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
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
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MaxSize 50
typedef int ElemType;
typedef struct
{
ElemType data[MaxSize];
int top;
} SqStack;
// 栈初始化
void InitSqStack(SqStack *&s)
{
s = (SqStack *)malloc(sizeof(SqStack));
if (s == NULL)
{
printf("内存分配失败\n");
exit(1);
}
s->top = -1;
}
// 判空
bool IsSqStackEmpty(SqStack *s)
{
return s->top == -1;
}
// 进栈
bool PushSqStack(SqStack *&s, ElemType e)
{
if (s->top == MaxSize - 1)
{
printf("栈满\n");
return false;
}
s->top++;
s->data[s->top] = e;
return true;
}
// 出栈
bool PopSqStack(SqStack *&s, ElemType &e)
{
if (IsSqStackEmpty(s))
{
printf("栈空\n");
return false;
}
e = s->data[s->top];
s->top--;
return true;
}
// 销毁栈
void DestroySqStack(SqStack *&s)
{
free(s);
s = NULL;
}
typedef struct LNode
{
ElemType data;
struct LNode *next;
} LinkList;
void InitLinkList(LinkList *&L)
{
L = (LinkList *)malloc(sizeof(LinkList));
if (L == NULL)
{
printf("内存分配失败\n");
exit(1);
}
L->next = NULL;
}
// 创建单链表
void CreateLinkList(LinkList *&L, ElemType arr[], int n)
{
InitLinkList(L);
LinkList *p = L;
for (int i = 0; i < n; i++)
{
LinkList *newNode = (LinkList *)malloc(sizeof(LinkList));
newNode->data = arr[i];
newNode->next = NULL;
p->next = newNode;
p = newNode;
}
}
// 遍历输出单链表
void PrintLinkList(LinkList *L)
{
LinkList *p = L->next;
if (p == NULL)
{
printf("单链表为空!\n");
return;
}
printf("原单链表元素:");
while (p != NULL)
{
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
void ReverseOutputBySqStack(LinkList *L)
{
SqStack *s;
InitSqStack(s);
LinkList *p = L->next;
while (p != NULL)
{
PushSqStack(s, p->data);
p = p->next;
}
printf("栈逆向输出:");
ElemType e;
while (!IsSqStackEmpty(s))
{
PopSqStack(s, e);
printf("%d ", e);
}
printf("\n");
DestroySqStack(s);
}
int main()
{
ElemType testArr[] = {10, 20, 30, 40, 50};
int n = sizeof(testArr) / sizeof(ElemType);
LinkList *L;
CreateLinkList(L, testArr, n);
PrintLinkList(L);
ReverseOutputBySqStack(L);
LinkList *p = L, *q;
while (p != NULL)
{
q = p->next;
free(p);
p = q;
}
return 0;
}