栈实现

顺序栈

#include <stdio.h>
#include <stdlib.h>
#define Maxsize 10
#define ElemType int
typedef struct {
ElemType *top;
ElemType *base;
int stacksize;//栈的大小
}SqStack;
int InitStack(SqStack *s){
s->base=(ElemType*)malloc(Maxsize*sizeof(ElemType));
if(!s){printf("栈创建失败\n");return 0;}
s->top=s->base;
s->stacksize=Maxsize;
return 1;
}//初始化栈
void StackEmpty(SqStack *s){
if(s->base==s->top){printf("栈为空\n");}
else {printf("栈不为空\n");}
}//判断栈是否为空
void PushStack(SqStack *s,ElemType e){
if(s->top-s->base>s->stacksize){printf("栈已满");}
else {
s->top++;
*(s->top)=e;
}
}//将元素e入栈
void PopStack(SqStack *s,ElemType e){
if(s->top==s->base){printf("栈以空");}
else{
e=*(s->top);
s->top--;
}
}//元素e出栈
ElemType GetTop(SqStack *s){
if(s->top==s->base){printf("栈以空");return 0;}
else return *(s->top);
}//获取栈顶元素
void PrintStack(SqStack *s){
ElemType *p;
p=s->base+1;
printf("栈元素为:");
while(p<=s->top){
printf("%d ",*p);
p++;
}
printf("\n");
}//打印出栈中元素
void main(){
SqStack S;
int e;
InitStack(&S);
StackEmpty(&S);
PushStack(&S,1);
PushStack(&S,2);
PushStack(&S,3);
PrintStack(&S);
printf("栈顶元素为:%d\n",GetTop(&S));
PopStack(&S,e);
PrintStack(&S);
StackEmpty(&S);
}

 

链栈(C++)

#include <stdio.h>
#include <stdlib.h>
#define ElemType int
typedef struct SLnode{
ElemType data;
struct SLnode *next;
}SLnode,*SLink;
void InitLstack(SLink &Lhead){
Lhead=(SLink)malloc(sizeof(SLnode));
if(!Lhead){printf("创建链栈失败\n");}
Lhead->next=NULL;
}//初始化链栈
void PushLstack(SLink &Lhead,ElemType e){
SLink r;
r=(SLink)malloc(sizeof(SLnode));
r->data=e;
r->next=Lhead;
Lhead=r;
}//将元素e入栈
void PopLstack(SLink &Lhead,ElemType e){
SLink r;
e=Lhead->data;
r=Lhead;
Lhead=Lhead->next;
printf("弹出的栈顶元素:%d\n",e);
free(r);
}//弹出栈顶元素
bool LstackEmpty(SLink &Lhead){
if(Lhead->next==NULL){printf("栈为空\n");return true;}
else {printf("栈不为空\n");return false;}
}//判断链栈是否为空
ElemType GetTop(SLink &Lhead){
return Lhead->data;
}//返回当前栈顶元素
void PrintLstack(SLink &Lhead){
printf("链栈元素为:");
SLink p=Lhead;
while(p->next!=NULL){
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}//打印链栈
int main(){
SLink Lhead;//链栈的头结点
int e;
InitLstack(Lhead);
LstackEmpty(Lhead);
PushLstack(Lhead,1);
PushLstack(Lhead,2);
PushLstack(Lhead,3);
PrintLstack(Lhead);
PopLstack(Lhead,e);
printf("当前栈顶元素:%d\n",GetTop(Lhead));
LstackEmpty(Lhead);
return 0;
}

 

转载于:https://www.cnblogs.com/Yshun/p/11160629.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值