#include <stdio.h>
#include <stdlib.h>
#define MaxSize 10
#define ElemType int
#define bool char
#define True 1
#define False 0
struct node {
ElemType data;
struct node *next;
};
struct node *top;
void init() {
top = NULL;
}
bool is_empty() {
if (top == NULL) {
return True;
} else {
return False;
}
}
void push(ElemType x) {
struct node *p;
p = (struct node *) malloc(sizeof(struct node));
p->data = x;
p->next = top;
top = p;
}
ElemType pop() {
if (is_empty()) {
printf("栈下溢错误!");
exit(1);
}
struct node *p;
ElemType x;
p = top;
x = p->data;
top = top->next;
free(p);
return x;
}
ElemType get_top() {
if (is_empty()) {
printf("栈下溢错误!");
exit(1);
}
return top->data;
}
int main() {
init();
for (int i = 1; i <= MaxSize; i++) {
printf("push(%d)\n", i);
push(i);
}
printf("get_top()->%d\n", get_top());
for (int j = 1; j <= MaxSize; j++) {
printf("pop()->%d\n", pop());
}
return 0;
}
栈的链式存储结构及基本操作
280 views