栈的数据结构定义及算法

来源:互联网 发布:液体卫生巾 知乎 编辑:程序博客网 时间:2024/05/16 14:22

顺序栈定义

typedef struct{    int data[maxSize];    int top;}SqStack;

顺序栈的基本操作

void initStack(Sqstack &st){    st.top = -1;}
判断栈为空

int isEmpty(SqStack st){if(st.top == -1)return 1;elsereturn 0;}

进栈操作

int Push(SqStack &st, int x){if(st.top == maxSize-1)    return 0;++(st.top);st.data[st.top] = x;   return 1;}

出栈操作

int Pop(SqStack &st, int &x){if(st.top == -1)   return 0;else   x = st.data[st.top] ;   --(st.top);   return 1;}

栈的应用

编写函数,求后缀表达式的值,其中后缀式存于一个数组exp中

例如 (a+b+c*d)/ e 其后缀式为 abcd*++e/

具体实现:

int op(int a, char op, int b){if(op == '+') return a+b;if(op == '-') return a-b;if(op == '*') return a*b;if((op == '/') &&(b != 0) return a/b;}int com(char exp[]){int i, a, b, c;int stack[maxSize];int top = -1;char op;for(i=0;exp[i] != '\0',++i){if(exp[i] >= '0' && exp[i] <= '9')stack[++top] = exp[i] - '0';else{op = exp[i];b = stack[top--];a = stack[top--];c = op(a,op,b);stack[++top] = c;}     }return stack[top];}


原创粉丝点击