栈简介
栈(stack)又名堆栈,它是一种运算受限的线性表。其限制是仅允许在表的一端进行插入和删除运算。这一端被称为栈顶,相对地,把另一端称为栈底。向一个栈插入新元素又称作进栈、入栈或压栈,它是把新元素放到栈顶元素的上面,使之成为新的栈顶元素;从一个栈删除元素又称作出栈或退栈,它是把栈顶元素删除掉,使其相邻的元素成为新的栈顶元素。
对于栈,只有两种操作:
1. push 先栈顶插入新元素,
2. pop 从栈顶删除元素
代码实现
栈底指针一直为NULL
ADT:
#include <stdio.h>
#define VTYPE char
typedef struct node {
VTYPE data;
struct node *next;
} stackNode, *stackNodePtr;
typedef struct {
stackNodePtr top;
stackNodePtr buttom;
} stack, *stackPtr;
stackPtr createStack();
void push(stackPtr s, VTYPE p);
void pop(stackPtr s);
void freeStack(stackPtr s);
完整代码:
#include <stdio.h>
#define VTYPE char
typedef struct node {
VTYPE data;
struct node *next;
} stackNode, *stackNodePtr;
typedef struct {
stackNodePtr top;
stackNodePtr buttom;
} stack, *stackPtr;
void push(stackPtr s, VTYPE p) {
stackNodePtr n = (stackNodePtr)malloc(sizeof(stackNode));
n->data = p;
n->next = s->top;
s->top = n;
}
void pop(stackPtr s) {
stackNodePtr n = s->top;
s->top = n->next;
free(n);
}
stackPtr createStack() {
stackPtr s = (stackPtr)malloc(sizeof(stack));
if (s == NULL)
return NULL;
s->top = s->buttom = NULL;
return s;
}
void freeStack(stackPtr s) {
while (s->top != NULL) {
pop(s);
}
}
void main() {
stackPtr s = createStack();
for (int i = 0; i < 10; i++) {
push(s, i);
}
freeStack(s);
}