Code Example:
#include "stdio.h"
#include "stdlib.h"
#define STACK_SIZE 10
typedef struct Stack {
char items[STACK_SIZE]; // 栈中数据
int top; // 栈顶位置
} Stack;
int init_stack(Stack *stack) {
/**
* 初始化栈:将栈顶指针置为-1
*/
if (stack != NULL) {
stack->top = -1;
return 1;
}
return 0;
}
int push(Stack *stack, char item) {
/**
* 入栈操作:如果栈没满,入栈
*/
if (stack->top < STACK_SIZE - 1) { // 栈未满
stack->top++;
stack->items[stack->top] = item;
return 1;
}
printf("\n栈满,数据'%c'并没有被插入", item);
return 0;
}
char pop(Stack *stack) {
/**
* 出栈操作:如果栈不为空,出栈
*/
char item;
if (stack->top != -1) { // 栈不为空
item = stack->items[stack->top];
stack->top--;
return item;
}
printf("\n栈空,请勿再弹出数据");
return NULL;
}
void main() {
// 定义栈
Stack *stack = malloc(sizeof(Stack));
// 栈初始化
init_stack(stack);
// 入栈
push(stack, 'a');
push(stack, 'b');
push(stack, 'c');
push(stack, 'd');
push(stack, 'e');
push(stack, 'f');
push(stack, 'g');
push(stack, 'h');
push(stack, 'i');
push(stack, 'j');
push(stack, 'k');
// 出栈
printf("\n出栈结果:");
for (int i = 0; i < 11; ++i) {
char item = pop(stack);
if (item != NULL) {
printf(" %c", item);
}
}
}
Output:
栈满,数据'k'并没有被插入
出栈结果: j i h g f e d c b a
栈空,请勿再弹出数据