?? 實驗表達式.cpp
字號:
#include<assert.h>
#include<iostream.h>
template <class Type>
class Stack
{
protected:
int top; //棧頂指針
Type *elements; //棧元素數(shù)組
int maxSize; //棧最大容量
public:
Stack ( int sz = 10 ); //構(gòu)造函數(shù)
~Stack ( ){ delete [ ] elements; }
void Push (Type item); //進棧
//void Pop( Type & item); //出棧
Type Pop();
Type GetTop (); //取棧頂
void Trans(Type str[],Type exp[]);
void Compvalve(Type exp[]);
void MakeEmpty ( ){ top=-1; }
int IsEmpty( )const { return top==-1;}
int IsFull ( ) const
{ return top==maxSize-1;}
};
template <class Type>
Stack<Type> ::Stack ( int s ) : top (-1), maxSize (s)
{
elements = new Type[maxSize];
assert ( elements != NULL ); //斷言
}
template <class Type>
void Stack<Type> ::Push ( Type item )
{
assert ( !IsFull ( ) ); //先決條件斷言
elements[++top] = item;
};
template <class Type>
Type Stack<Type>::Pop()
{
Type Item;
if(IsEmpty()==1)return 0;//棧空不退棧
Item=elements[top];
top--;
return Item ;
//退出棧頂元素
}
template <class Type>
Type Stack<Type>::GetTop ( )
{
assert (!IsEmpty( )); //先決條件斷言
if(IsEmpty())return 0;
return elements[top] ; //取出棧頂元素
}
/////////////////////////////////////////////////////////
template <class Type>
void Stack<Type>::Trans(Type str[],Type exp[])//轉(zhuǎn)換成波蘭式
{
Type ch;
int i,k;
k=0,i=0;
ch=str[i];
i++;
while(ch!='#')
{
if(ch>='0'&&ch<='9')
{exp[k++]=ch;}
else if( ch== '(' )Push(ch);
else if( ch== ')' )
{
while( GetTop()!= '(' )
{
exp[k++]=Pop();
}
Pop();
}
else if(ch=='+'||ch=='-')
{
while(IsEmpty()!=1&&GetTop()!= '(' )
{
exp[k++]=Pop();
}
Push(ch);
}
else if(ch=='*'||ch=='/')
{
while(GetTop()=='*'||GetTop()=='/')
{
exp[k++]=Pop();
}
Push(ch);
}
ch=str[i++];
}
while(IsEmpty()!=1)
{
exp[k++]=Pop();
}
exp[k]='#';
for(int j=0;j<k;j++)
cout<<exp[j];
cout<<endl;
}
template <class Type>
void Stack<Type>::Compvalve(Type exp[])//計算
{
char c;
int i=0,k=0,top=-1;
while(exp[k]!='#')k++;
c=exp[i++];
float stack[100],data;
while(c!='#')
{
data=c-'0'; //將字符轉(zhuǎn)換成數(shù)字
if(c>='0'&&c<='9')stack[++top]=data;
else
{
switch (c)
{
case'+': stack[top-1]=stack[top-1]+stack[top];break;
case'-': stack[top-1]=stack[top-1]-stack[top];break;
case'*': stack[top-1]=stack[top-1]*stack[top];break;
case'/':
{
if(stack[top]!=0)
stack[top-1]=stack[top-1]/stack[top];
else cout<<"除數(shù)為0!"<<endl;
break;
}
}
top--;
}
c=exp[i++];
}
cout<<stack[top]<<endl;
}
void main()
{
typedef Stack<char> IntStack;
IntStack st(100);
int k=0;
char a;
char str[100],exp[100];
cin>>a;
while(a!='#')
{
str[k++]=a;
cin>>a;
}
st.Trans(str,exp);
cout<<"結(jié)果為:";
st.Compvalve(exp);
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -