#include <stdio.h>
#include <stdlib.h>
typedef int ElemType;
typedef struct StackNode{
ElemType data;
struct StackNode *next;
}StackNode;
StackNode *InitStack(StackNode *S);//初始化
StackNode * DestroyStack(StackNode*S);//销毁
void ClearStack(StackNode*S);//清空
int StackEmpty(StackNode*S);//判空
int StackLength(StackNode*S);//栈长度
ElemType GetTop(StackNode*S);//获取栈顶元素,不修改指针位置
StackNode *Push(StackNode*S, ElemType e);//插入栈顶
StackNode *Pop(StackNode *S, ElemType *e);//删除栈顶
void StackTraverse(StackNode *S);//从栈顶依次遍历
//初始化
StackNode *InitStack(StackNode *S){
S = NULL;
printf("初始化成功\n");
return S;
}
//销毁,返回空指针给S
StackNode *DestroyStack(StackNode*S){
StackNode *p = S->next;
while(p){
free(S);
S = p;
p = p->next;
}
printf("销毁成功\n");
return NULL;
}
//清空
void ClearStack(StackNode*S){
printf("清空\n");
StackNode *p = S;
while(p!=NULL){
p->data = ;
p = p->next;
}
printf("清空成功\n");
}
//判空
int StackEmpty(StackNode*S);
//栈长度
int StackLength(StackNode*S){
int len = ;
StackNode *p = S;
while(p!=NULL){
len++;
p = p->next;
}
return len;
}
//获取栈顶元素,不修改指针位置
ElemType GetTop(StackNode*S){
if(S!=NULL){
printf("栈顶元素为%d", S->data);
return S->data;
}else{
printf("空链栈无栈顶元素\n");
return NULL;
}
}
//插入栈顶,返回指针指向当前栈顶
StackNode *Push(StackNode*S, ElemType e){
StackNode *p = NULL;
p = (StackNode *)malloc(sizeof(StackNode));
p->data = e;
p->next = S;
S = p;
printf("%d入栈成功\n", e);
return S;
}
//删除栈顶,返回指针指向当前栈顶
StackNode *Pop(StackNode *S, ElemType *e){
StackNode *p = NULL;//用于暂存删除元素
if(S == NULL){
printf("空链栈,删除失败\n");
return NULL;
}
*e = S->data;
p = S;
S = S->next;
free(p);
printf("%d出栈成功\n",*e);
return S;
}
//从栈顶依次遍历
void StackTraverse(StackNode *S){
StackNode *p = S;
if(p == NULL){
printf("空链栈\n");
return;
}
while(p != NULL){
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main(void){
StackNode *S;
ElemType e;
//初始化测试
S = InitStack(S);
// //获取栈顶元素测试
// GetTop(S);
// S = Push(S, 999);
// GetTop(S);
//入栈测试
S = Push(S, );
S = Push(S, );
S = Push(S, );
S = Push(S, );
S = Push(S, );
//栈长测试
printf("栈长%d\n",StackLength(S));
//遍历测试
StackTraverse(S);
// //出栈测试
// S = Pop(S, &e);
// S = Pop(S, &e);
// S = Pop(S, &e);
// //printf("测试e是否改变: %d\n",e);
// S = Pop(S, &e);
// StackTraverse(S);
// //清空测试
// ClearStack(S);
// StackTraverse(S);
//// //销毁测试
// S = DestroyStack(S);
// StackTraverse(S);
return ;
}