One-day-one-program(7)之顺序栈的实现

来源:互联网 发布:个体工商户域名备案 编辑:程序博客网 时间:2024/05/18 02:58

 栈是一种特殊的线性表,它限定了线性表的插入、删除操作只能在线性表的一端进行这一端叫做栈顶。

 栈的基本运算:

(1)栈初始化:Init_stack(s)

(2)判栈空:Empty_stack(s)

(3)入栈(压栈):Push_stack(s,x)

(4)出栈(弹出):Pop_stack(s)
   
(5)读栈顶元素:Top_stack(s)

#include<stdio.h>#include<stdlib.h>#define MAXSIZE 100typedef struct{int data[MAXSIZE];int top;}SeqStack;SeqStack* Init_SeqStack()//置空栈{SeqStack *S;S=(SeqStack*)malloc(sizeof(SeqStack));S->top=-1;return S;}int Push_SeqStack(SeqStack *S,int x)//入栈{if(S->top==MAXSIZE-1)return 0;else{S->top++;S->data[S->top]=x;return 1;}}int Empty_SeqStack(SeqStack *S)//判空栈{if(S->top==-1)return 1;elsereturn 0;}int Pop_SeqStack(SeqStack *S,int *x)//出栈{if(Empty_SeqStack(S)==1)return 0;else{*x=S->data[S->top];S->top--;return 1;}}int Top_SeqStack(SeqStack *S)//读栈顶元素{if(Empty_SeqStack(S)==1)return -1;elsereturn(S->data[S->top]);}void main(){SeqStack *S;S=Init_SeqStack();int x;int r1,r2;int i;int a;printf("请输入你要存入的数据:\n");scanf("%d",&x);while(x!=-1){r1=Push_SeqStack(S,x);scanf("%d",&x);}printf("此栈的栈顶元素为:\n");r2=Top_SeqStack(S);printf("%d\n",r2);printf("栈中存储的数据为:\n");while(Pop_SeqStack(S,&a)!=0){printf("%d\n",a);}}


 

0 0
原创粉丝点击