stack的数组实现

来源:互联网 发布:mac玩lol国服 编辑:程序博客网 时间:2024/06/05 18:59
//stack的数组实现(方法类似于类的定义)
//1:实现栈的数据定义
//2:实现操作方法的定义push pop empty full top(并不需要,因为stack[top]就是top)



//ps:栈的使用过程是先创建栈对象,然后再对此对象进行相关操作。栈定义中的top这里指定为栈顶的数组下标,top指向的是存在的数据。

//ps:在采用数组实现栈时,数组0下标对应的是栈底,top下标对应的是栈顶

#include <stdio.h>#define  MAXSIZE 100struct node{int a;char b;};//1的实现struct stack{node n[MAXSIZE];//这里定义n[0]为栈底int top;};//2的实现bool emptyStack(stack *s) { if(s->top==-1) return true; return false; }bool fullStack(stack *s){if(s->top==MAXSIZE-1)return true;return false;}bool pushStack(stack *s ,node p){if(fullStack(s))return 0;s->top++;s->n[s->top]=p;return 1;}bool popStack(stack *s){if(emptyStack(s))return false;s->top--;return true;}void main(){stack s;s.top=-1;node a={1,'f'};node b={2,'e'};node c={3,'g'};pushStack(&s,a);pushStack(&s,b);pushStack(&s,c);printf("%2d\n",s.n[0].a);printf("%2d\n",s.n[1].a);printf("%2d\n",s.n[s.top].a);popStack(&s);printf("%2d\n",s.n[s.top].a);}