栈的功能
//栈的顺序存储
//stack.h
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 100
typedef char ElemType;
typedef struct //SqStack
{
ElemType a[MAXSIZE];
int top;
}SqStack;
void init_s(SqStack *s)
{
s=(SqStack *)malloc(sizeof(SqStack));
s->top=-1;
}
/******************************检测完毕*****************************/
void out_s(SqStack *s)//print the elems of the stack
{
int i;
if(s->top==-1) printf("\n Stack is NULL");
else{ i=s->top;
while(i!=-1)
{printf("\n data[%d]=%c", i,s->a[i]);i--;}
}
}
/****************************检测完毕*******************************/
void push(SqStack *s,ElemType e)
{
if(s->top==MAXSIZE-1)printf("\n Stack is overflow!");
else{fflush(stdin);s->top++;
s->a[s->top]=e;
}
}
/*********************检测完毕**************************************/
ElemType pop(SqStack *s)
{
ElemType x;
if(s->top==-1) {printf("\n Stack is NULL");x=-1;}
else{x=s->a[s->top];s->top--;}
return x;
}
利用栈表达式求值
//stack.cpp
#include<stdio.h>
#include<stdlib.h>
#include"stack.h"//计算符号栈栈
SqStack st;//符合栈
SqStack st2;//数字栈
void PostfixExpress(char *exp,char *postexp);//后缀表达式
float compvalue(char *postexp);//后缀表达式求解
void main()
{
char *ss,*postss;
float f;
ss=(char *)malloc(MAXSIZE*sizeof(char));
postss=(char *)malloc(MAXSIZE*sizeof(char));
printf("输入中序表达式:(#结尾)");
fflush(stdin);
scanf("%s",ss);
//printf("你输入的中序表达式是:%s\n",ss);
PostfixExpress(ss,postss);
printf("表达式的后缀形式是:%s\n",postss);
f=compvalue(postss);
printf("计算结果是:%f\n",f);
}
void PostfixExpress(char *exp,char *postexp)
{
init_s(&st);
// push(&st,'#');out_s(&st);
int i=0;
ElemType c;
while(*exp!='#' && st.top!=-1)
{
switch(*exp)
{
case '(':
push(&st,*exp);
exp++;
break;
case ')':
while(st.a[st.top]!='(')/************/
{
c=pop(&st);
postexp[i++]=c;
}
c=pop(&st);
exp++;
break;
case '+':
case '-':
while(st.a[st.top]!=0 && st.a[st.top]!='(')
{
c=pop(&st);
postexp[i++]=c;
}
push(&st,*exp);
exp++;
break;
case '*':
case '/':
c=pop(&st);
push(&st,c);
while(c=='*' || c=='/')
{
c=pop(&st);
postexp[i++]=c;
}
push(&st,*exp);
exp++;
break;
case ' ':break;
default:
while(*exp>='0' && *exp<='9')
{
postexp[i++]=*exp;
exp++;
}
postexp[i++]='#';
}
}
while(st.top!=-1)
{
c=pop(&st);
postexp[i++]=c;
}
postexp[i]='\0';
}
float compvalue(char *postexp)
{
//st2=(SqStack2 *)malloc(sizeof(SqStack2));
init_s(&st2);
float a,b,c,d,e;
while(*postexp!='\0')
{
switch(*postexp)
{
case '+':
a=pop(&st2);b=pop(&st2);
c=a+b;
push(&st2,c);//out_s2(&st2);
break;
case '-':
a=pop(&st2);b=pop(&st2);c=b-a;
push(&st2,c);//out_s2(&st2);
break;
case '*':
a=pop(&st2);b=pop(&st2);c=b*a;
push(&st2,c);//out_s2(&st2);
break;
case '/':
a=pop(&st2);b=pop(&st2);
if(a!=0) {c=b/a;push(&st2,c);;}
else {printf("\n零不能为被除数!\n");exit(0);}
break;
default://处理数字字符
if(*postexp!='#' && *postexp!='\0')
{ d=0;
while(*postexp>='0' && *postexp<='9')
{
//printf("%d",*postexp);
d=10*d+*postexp-'0';
postexp++;
}
push(&st2,d);
}
break;
}
postexp++;
}
e=pop(&st2);//printf("%f",e);
return (e);
}
/