1.代码的运行
#include <stdio.h>
#include <malloc.h>
#define STACK_MAX_SIZE 10
typedef struct CharStack {
int top;
char data[STACK_MAX_SIZE]; //设置最大长度
} *CharStackPtr;
//栈的输出
void outputStack(CharStackPtr paraStack) {
for (int i = 0; i <= paraStack->top; i ++) {
printf("%c ", paraStack->data[i]);
}
printf("\r\n");
}
//栈的初始化
CharStackPtr charStackInit() {
CharStackPtr resultPtr = (CharStackPtr)malloc(sizeof(struct CharStack));
//初始值为-1,表示栈为空
resultPtr->top = -1;
return resultPtr;
}
//入栈
void push(CharStackPtr paraStackPtr, int paraValue) {
// 先看是否有存放空间
if (paraStackPtr->top >= STACK_MAX_SIZE - 1) {
printf("Cannot push element: stack full.\r\n");
return;
}
// top指针向上指一个
paraStackPtr->top ++;
// 把数据放进去
paraStackPtr->data[paraStackPtr->top] = paraValue;
}
char pop(CharStackPtr paraStackPtr) {
// 检查
if (paraStackPtr->top < 0) {
printf("Cannot pop element: stack empty.\r\n");
return '\0';
}//健壮性更强
// 更新
paraStackPtr->top --;
return paraStackPtr->data[paraStackPtr->top + 1];
}
void pushPopTest() {
char ch;
int i;
printf("---- pushPopTest begins. ----\r\n");
CharStackPtr tempStack = charStackInit();
printf("After initialization, the stack is: ");
outputStack(tempStack);
for (ch = 'a'; ch < 'm'; ch ++) {
printf("Pushing %c.\r\n", ch);
push(tempStack, ch);
outputStack(tempStack);
}
for (i = 0; i < 3; i ++) {
ch = pop(tempStack);
printf("Pop %c.\r\n", ch);
outputStack(tempStack);
}
printf("---- pushPopTest ends. ----\r\n");
}
int main() {
pushPopTest();
return 0;
}
2.运行结果
a b c d
Pushing e.
a b c d e
Pushing f.
a b c d e f
Pushing g.
a b c d e f g
Pushing h.
a b c d e f g h
Pushing i.
a b c d e f g h i
Pushing j.
a b c d e f g h i j
Pushing k.
Cannot push element: stack full.
a b c d e f g h i j
Pushing l.
Cannot push element: stack full.
a b c d e f g h i j
Pop j.
a b c d e f g h i
Pop i.
a b c d e f g h
Pop h.
a b c d e f g
---- pushPopTest ends. ----
3.思考
(1)利用固定大小的数组 data[STACK_MAX_SIZE]
来存储栈中的元素,这种方式简单直接,但也有局限性,即栈的最大容量是固定的,当栈满时无法再添加新元素。
(2)代码中没有对应的 free
操作来释放栈所占用的内存,在实际应用中,为了避免内存泄漏,应该在栈不再使用时调用 free
函数释放内存。
(3) 编写测试函数是保证代码质量的重要手段,能够及时发现代码中的问题。