实验项目二:栈的基本操作及其应用

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<stdlib.h>
#include<stdio.h>
#include<stack>
#define  MAXSIZE  100
#define  OVERFLOW  0
using namespace std;

typedef struct{           //栈存储空间的初始分配量 
 	int  *base;     //栈底指针 
 	int  *top;  	//栈顶指针 
 	int stacksize;     //栈可用的最大容量 
 }Sqstack;
 
bool  In(char ch)  //判断c是否为运算符
{
	if(ch=='+' || ch=='-' || ch=='*' || ch=='/' || ch=='(' || ch==')' || ch=='#')
		return true;
	else
		return false;
}

char Precede(char t1,char t2)     //判断两个运算符的优先关系
{ 
   char f;
   if(t2=='#')
   {	if(t1!='#'&&t1!='(')
   			f='>';
   		if(t1=='#') 
   			f='=';
   }
   else if(t2=='+'||t2=='-')
   {
   	    if(t1=='+'||t1=='-'||t1=='*'||t1=='/'||t1==')') 
     		f='>';
     	else 
     		f='<';
   }
   else if(t2=='*'||t2=='/')
   {
   		if(t1=='+'||t1=='-'||t1=='#'||t1=='('||t1=='#') 
     		f='<';
     	else 
     		f='>';
   }
   else if(t2=='(')
   {
   		if(t1=='+'||t1=='-'||t1=='#'||t1=='*'||t1=='/'||t1=='(') 
     		f='<';
     	
   }
   else if(t2==')')
   {
   		if(t1=='+'||t1=='-'||t1=='*'||t1=='/'||t1==')') 
     		f='>';
     	if(t1=='(')
     		f='=';
   }
   else if(t1=='+'||t1=='-'||t1=='#'||t1=='*'||t1=='/'||t1=='('||t1==')')
   {
   		f='>';
   }
	return f;
}

int  Operate(int a,char theta,int b)
{   if(theta=='+')
		return a+b;
	else if(theta=='-')
		return a-b;
	else if(theta=='*')
		return a*b;
	else if(theta=='/')
		return a/b;	
}

bool initstack(Sqstack &S)    //初始化 
 {
 	S.base =new int[MAXSIZE];   //为栈分配一个最大容量为MAXSIZE的数组空间 
 	if(!S.base )  exit(OVERFLOW);  //存储分配失败 
 	S.top =S.base ;               //top初始为base,空栈 
 	S.stacksize =MAXSIZE;     	//stacksize置为栈的最大容量MAXSIZE 
 	return true;
 }

bool push(Sqstack &S, char e)  //入栈 
{
	if(S.top -S.base ==S.stacksize )  return  false;
	*S.top ++=e;
	return true;
}

bool pop(Sqstack &S, char &e)   //出栈 
{
	if(S.top ==S.base )  return false;
	e=*--S.top ;
	return true;
 } 

int gettop(Sqstack S)     //取栈顶元素 
{
	if(S.top!=S.base)
	return *(S.top-1);
}

int EvaluateExpression()  //OPTR为运算符栈,OPND为操作数栈 
{	char ch,theta;
	char a,b,x;
	int c,v;
	Sqstack OPND,OPTR;
	initstack(OPND);   //初始化OPND栈 
	initstack(OPTR);   //初始化OPTR栈 
	push(OPTR,'#');
	cin>>ch;
	while(ch!='#' || gettop(OPTR)!='#')
	{
		if(!In(ch))  
		{
			push(OPND,ch-48);
			cin>>ch;
		}
		else
		{
			switch(Precede(gettop(OPTR),ch))
			{
			   case '<':{
			   	push(OPTR,ch);
			   	cin>>ch;
				break;
			   }
			   case '>':{
			   	pop(OPTR,theta);
			   	pop(OPND,b);
			   	pop(OPND,a);
			   	c=a;
			   	v=b;
			   	push(OPND,Operate(c,theta,v));
			   	cout<<c<<theta<<v<<"="<<Operate(c,theta,v)<<endl;
				break;
			   }
			   case '=':{
			   	pop(OPTR,x);
			   	cin>>ch;
				break;
			   }	
			}
		 } 
		
	}
	return gettop(OPND);
 } 

int main()
 {
 	while(1)
 	{ 
	 	printf("请输入英文输入法的算术表达式,并以#结束.\n");
  		printf("如果我没算错的话,答案是:%d\n",EvaluateExpression());
 		
	 }
 
  return 0;
 }











猜你喜欢

转载自blog.csdn.net/sang_12345/article/details/78522671