顺序栈
#include <stdio.h>#include <stdlib.h>#define Maxsize 10#define ElemType inttypedef 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 inttypedef 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
相关资源:顺序栈,压栈、弹栈、获得栈顶元素、统计栈中元素个数、打印栈中元素