/* 链栈的基本功能及实现
与顺序栈大同小异,仅在结构体处做改变,可去对比前一篇顺序栈的实现
结构体要求:单链表的头结点当做栈顶指针
类似于头插法的链表(但限制为:只在头结点出,头结点进)
*/
#include <stdio.h>
#include <stdlib.h>
typedef int ElemType;
typedef struct StackNode{//链栈结构体
ElemType data;//数据域
struct StackNode *next;
}StackNode,*LinkStack;
//方法体实现
//创
bool InitLinkStack(LinkStack &S){//初始化链栈 (ps:链栈不需要设头结点,直接每次让新加入的结点作为头结点就行(也就是栈顶))
S = NULL;//链栈判空条件
return true;
}
bool CreateLinkStack(LinkStack &S){//创建链栈
InitLinkStack(S);
printf("\n请依次输入 入栈元素,输入-9999结束\n");
ElemType elem;
scanf("%d",&elem);
while(elem!=-9999){// 头插法入栈(可以使用入栈方法)
StackNode *p = (StackNode *)malloc(sizeof(StackNode));
p->data = elem;
p->next = S;
S = p;//每次都让头结点为新加入的结点
scanf("%d",&elem);
}
return true;
}
//增(入栈,只在头结点处入)
bool PushLinkStack(LinkStack &S,ElemType e){//将e入栈
StackNode *p = (StackNode *)malloc(sizeof(StackNode));
p->data = e;
p->next=S;
S = p;
printf("\n入栈成功!\n");
return true;
}
//删(出栈,只在头结点处出)
ElemType PopLinkStack(LinkStack &S,ElemType &result){//如果只想查栈顶元素,则不需要更改头结点的next域
if(S==NULL){//判断栈空
printf("\n栈为空!\n");
return result;
}
//可出栈
StackNode *d = (StackNode *)malloc(sizeof(StackNode));//指向删除结点的工作指针
d = S;
S =d->next;
result = d->data;
delete(d);
return result;
}
//查
bool ShowLinkStack(LinkStack S){
if(S==NULL){
printf("\n栈为空!\n");
return false;
}
printf("\n栈为:\n");
while(S!=NULL){
printf("%d\t",S->data);
S = S->next;
}
return true;
}
int main(){
StackNode *S = (StackNode *)malloc(sizeof(StackNode));
CreateLinkStack(S);
ShowLinkStack(S);
printf("\n入栈测试!");
PushLinkStack(S,21212);
ShowLinkStack(S);
printf("\n出栈测试!");
ElemType result = PopLinkStack(S,result);
printf("\n出栈元素为:%d",result);
ShowLinkStack(S);
}
链栈基本操作实现——C语言
最新推荐文章于 2023-09-09 08:00:00 发布