#include "stdio.h"
#include "stdlib.h"
#include "math.h"
#include "time.h"
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define MAXSIZE 20 /* 存储空间初始分配量 */
typedef int Status;
typedef int SElemType; /* SElemType 类型根据实际情况而定,这里假设为 int */
/*节点*/
typedef struct StackNode {
SElemType data;
struct StackNode *next;
} StackNode, *LinkStackPtr;
/*链栈*/
typedef struct {
LinkStackPtr top;//栈顶节点,每次只能对栈顶的节点进行操作,所以这么设定
int count;
} LinkStack;
/*打印一个节点的值*/
Status visit(SElemType c) {
printf("%d", c);
return OK;
}
/* 构造一个空栈 S */
Status InitStack(LinkStack *S) {
S->top = (LinkStackPtr)malloc(sizeof(StackNode));
if (!S->top)
return ERROR;
S->top = NULL;
S->count = 0;
return OK;
}
/* 把 S 置为空栈 */
Status ClearStack(LinkStack *S) {
LinkStackPtr p, q;
p = S->top;//栈顶节点
while (p) {
q = p;
p = p->next;
free(q);
}
S->count = 0;
return OK;
}
/* 若栈 S 为空栈,则返回 TRUE,否则返回 FALSE */
Status StackEmpty(LinkStack S) {
if (S.count == 0)
return TRUE;
else
return FALSE;
}
/* 返回 S 的元素个数,即栈的长度 */
int StackLength(LinkStack S) {
return S.count;
}
/* 若栈不空,则用 e 返回 S 的栈顶元素,并返回 OK;否则返回 ERROR */
Status GetTop(LinkStack S, SElemType *e) {
if (S.top == NULL)
return ERROR;
else
*e = S.top->data;
return OK;
}
/* 插入元素 e 为新的栈顶元素 */
Status Push(LinkStack *S, SElemType e) {
//创建一个当前要操作的节点小s
LinkStackPtr s = (LinkStackPtr)malloc(sizeof(StackNode));
s->data = e; //为新节点赋值
s->next = S->top;//新的节点指向栈顶节点
S->top = s; //栈顶指针指向新的节点
S->count++; //栈内的元素数+1
return OK;
}
/* 若栈不空,则删除 S 的栈顶元素,用 e 返回其值,并返回 OK;否则返回 ERROR */
int Pop(LinkStack *S, SElemType *e) {
LinkStackPtr p;
if (StackEmpty(*S))//如果栈是空的
return ERROR;
*e = S->top->data;
p = S->top;
S->top = S->top->next;
free(p);
S->count--;
return OK;
}
/* 将栈顶结点赋值给 p,见图中3 */
/* 使得栈顶指针下移一位,指向后一结点,见图中4 */
/* 释放结点 p */
Status StackTraverse(LinkStack S) {
LinkStackPtr p;
p = S.top;
while (p) {
visit(p->data);
p = p->next;
}
printf("
");
return OK;
}
int main() {
int j;
LinkStack s;
int e;
if (InitStack(&s) == OK)
for (j = 1; j <= 10; j++)
Push(&s, j);
printf("栈中元素依次为:");
StackTraverse(s);
Pop(&s, &e);
printf("弹出的栈顶元素 e=%d
", e);
printf("栈空否:%d(1:空 0:否)
", StackEmpty(s));
GetTop(s, &e);
printf("栈顶元素 e=%d 栈的长度为%d
", e, StackLength(s));
ClearStack(&s);
printf("清空栈后,栈空否:%d(1:空 0:否)
", StackEmpty(s));
return 0;
}