栈是一种特殊的线性表,LIFO。
数据类型:
typedef int elemtype;
typedef int status;
typedef struct snode {
elemtype data;
struct lnode *next;
}snode,*linkstack;
链栈初始化: 同线性表
status initstack(linkstack *s) {
if (s == NULL) return ERROR;
*s = (linkstack)malloc(sizeof(snode));
if (!*s)return ERROR;
(*s)->next = NULL;
return OK;
}
链栈销毁:同线性表
status destroystack(linkstack *s) {
if (s == NULL || *s == NULL)return ERROR;
linkstack p;
while (*s) {
p = (*s)->next;
free(*s);
*s = p;
}
return OK;
}
压栈:不需要判断插入位置是否合理,不需要求出第i-1个元素
status pushstack(linkstack s,elemtype e) {
if (s == NULL)return ERROR;
linkstack new;
new = (linkstack)malloc(sizeof(snode));
if (!new)return ERROR;
new->data = e;
new->next = s->next;
s->next = new;
return OK;
}
出栈:
status popstack(linkstack s, elemtype *e) {
if (s == NULL||e==NULL)return ERROR;
if (!s->next) return ERROR;
linkstack q;
q = s->next;
s->next = q->next;
*e = q->data;
free(q);
return OK;
}