链栈的基本操作有如下几种:入栈,出栈,判断栈满,判断栈空,遍历栈
详情请见testcase:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define STACK_MAX 3
typedef struct stack {
char data[10];
struct stack *next;
} *st_ptr;
int is_stack_empty(st_ptr top) {
if (top->next) {
return -1;
}
return 0;
}
int is_stack_full(st_ptr top) {
st_ptr tmp = top;
int cur = 0;
while (tmp->next) {
cur++;
tmp = tmp->next;
}
if (cur == STACK_MAX) {
return 0;
}
return -1;
}
void print_stack(st_ptr top) {
st_ptr tmp = top;
while (tmp->next) {
printf("%s\n", tmp->next->data);
tmp = tmp->next;
}
printf("\n");
}
int push_stack(st_ptr top, st_ptr pop) {
if (is_stack_full(top) == 0) {
printf("stack full, can not push\n");
return -1;
}
pop->next = top->next;
top->next = pop;
return 0;
}
int pop_stack(st_ptr top) {
if (is_stack_empty(top) == 0) {
printf("stack empty, can not pop\n");
return -1;
}
top->next = top->next->next;
return 0;
}
int main() {
st_ptr top, cheny, cherry, new, test;
top = (st_ptr)malloc(sizeof(struct stack));
cheny = (st_ptr)malloc(sizeof(struct stack));
cherry = (st_ptr)malloc(sizeof(struct stack));
new = (st_ptr)malloc(sizeof(struct stack));
test = (st_ptr)malloc(sizeof(struct stack));
// this is an empty stack
top->next = NULL;
if (is_stack_empty(top) == 0) {
printf("stack empty\n\n");
}
strcpy(cheny->data, "cheny");
push_stack(top, cheny);
print_stack(top);
strcpy(cherry->data, "cherry");
push_stack(top, cherry);
print_stack(top);
strcpy(new->data, "new");
push_stack(top, new);
print_stack(top);
if (is_stack_full(top) == 0) {
printf("stack full\n\n");
}
push_stack(top, test);
pop_stack(top);
pop_stack(top);
print_stack(top);
pop_stack(top);
if (is_stack_empty(top) == 0) {
printf("stack empty\n\n");
}
pop_stack(top);
return 0;
}
运行结果如下:
stack empty
cheny
cherry
cheny
new
cherry
cheny
stack full
stack full, can not push
cheny
stack empty
stack empty, can not pop
程序的大致意思是:建立一个空栈,然后入栈3个元素(栈的空间是3),所以此时栈满,不能再入栈了(结果有打印哦),然后出栈2个,此时遍历栈(栈中只有1个了),然后再出栈1个,所以此时栈空,不能再出栈了(结果也有打印哦)