栈、队列算法设计

来源:互联网 发布:大数据有关的课题 编辑:程序博客网 时间:2024/05/21 17:33
这是我数据结构实验的程序,参照了有关数据结构(C语言)书中的程序。
#include<iostream.h>
#define elemtype char
const maxsize=1000;
elemtype s1[maxsize],s2[maxsize];//存放中缀,后缀
struct seqstack  //定义顺序栈
{ elemtype stack[maxsize];
int top;
};
seqstack inistack(seqstack S)//栈的初始化
{
 S.top=0;
 return S;
}
seqstack push(seqstack S,elemtype x)//进栈
{
S.top++;
S.stack[S.top]=x;
return S;
}
seqstack pop(seqstack S) //退栈
{
 S.top--;
 return S;
}
elemtype gettop(seqstack S)//取栈顶元素
{
 return S.stack[S.top];
}
int empty(seqstack S)//判栈空
{
 if(S.top==0) return 1;
 else return 0;
}
int oper(elemtype op)//返回运算符的优先级
{
 switch(op){
 case'+':case'-':return 1;
 case'*':case'/':return 2;
 case'(':return 0;
 default :return 0;
 }
}
void change()//中缀式转换成等价的后缀表达式
{
 seqstack S;elemtype y,ch;S.top=0;
 S=inistack(S);S=push(S,'@');
 int i=0,j=0;
ch=s1[i];
while(ch!='@')
{
 if(ch==' ')ch=s1[++i];
 else if(ch=='('){S=push(S,ch);ch=s1[++j];}//进栈
 else if (ch==')'){y=gettop(S);//退栈
 while (y!='(')
 {
  s2[j++]=y;s2[j++]=' ';S=pop(S);y=gettop(S);}
 S=pop(S);ch=s1[++i];}
 else if((ch=='+')||(ch=='-')||(ch=='*')||(ch=='/'))
 {
  y=gettop(S);if(oper(ch)>oper(y)) {S=push(S,ch);ch=s1[++i];}
  else {y=gettop(S);s2[j++]=y;s2[j++]=' ';S=pop(S);}}
 else
 {
  while(((ch>='0')&&(ch<='9'))||(ch=='.'))
  {
   s2[j++]=ch;ch=s1[++i];}
  s2[j++]=' ';
 }
}
y=gettop(S);
while(y!='@')
{
 s2[j++]=y;s2[j++]=' ';S=pop(S);y=gettop(S);}
s2[j]='@';
}
void main()
{
 elemtype ch ,int i= 0;
 cout<<"请输入中缀表达('@'结束):";
 cin>>ch;
 while(ch!='@')
 {s1[i++]=ch;cin>>ch;}
 s1[i]='@';
 cout<<"中缀表达式为:"<<endl;
 for(int j=0;j<i;j++) cout<<s1[j];
 cout<<endl;
 change();
 cout<<"后缀表达式为: ";
 cout<<endl;
 j=0;
 while(s2[j]!='@')
 {cout<<s2[j];
 j++;
 }
 cout<<endl;
}
原创粉丝点击