|
C++ stack 的问题,
我要把 infix 换成 postfix , 然后做简单的calculation.
有什么最简单的 code 吗? 上网找了, 找到了一两个, 都不明白。小弟要最基本简单, 没有什么 class pub , pri 的。 帮帮忙, 谢谢 |
|
|
|
|
|
|
|
发表于 2-1-2007 09:36 AM
|
显示全部楼层
先去明白stack的theory吧 |
|
|
|
|
|
|
|

楼主 |
发表于 2-1-2007 10:18 AM
|
显示全部楼层
原帖由 <i>ReyesChuah</i> 于 2-1-2007 09:36 AM 发表<br />
先去明白stack的theory吧<img src="images/smilies/sweat.gif" smilieid="32" border="0" alt="" /> <br />
我们学很基本的。 什么是class 都不知道。
http://img54.imageshack.us/img54/8219/ansos4.gif
该如何解决哪个乱吗?想不到。
// the program is used to convert a infix expression to a postfix expression
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
const int size =50;
char infix[size],postfix[size],stack[size];
int top=-1;
int precedence(char ch); // function to get the precedence of the operator
char pop(); //function to pop an element from the stack
char topelement(); // returns the top element of the stack
void push(char ch); // pushes an element into the stack
int main()
{
char ele=0,elem=0,st[2];
int prep=0,pre=0,popped=0, j=0,chk=0,op1=0,op2=0,result=0;
strcpy(postfix," ");
//gets(infix);
cout<<"Enter expression: ";
cin>>infix;
for(int i=0;infix!=0;i++)
{
if(infix!='('&&infix!=')'&&infix!='*'&&infix!='/'&&infix!='+'&&infix!='-')
postfix[j++]=infix;
else if(infix=='(')
{
elem=infix;
push(elem);
}
else if(infix==')')
{
while(popped=pop() != '(')
postfix[j++]=popped;
}
else
{
elem=infix;
pre=precedence(elem);//stores the precedence of operator coming frm infix
ele=topelement();
prep=precedence(ele);//stores the precedence of operator at the top of the stack
if(pre > prep)
push(elem);
else
{
while(prep >= pre)
{
if(ele=='#')
break;
popped=pop();
ele=topelement();
postfix[j++]=popped;
prep=precedence(ele);
}
push(elem);
}
}
}
while((popped=pop())!='#')
postfix[j++]=popped;
postfix[j]='\0';
cout<<"\n post fix :"<<postfix<<endl;
system("pause");
return 0;
}
int precedence(char ch)
{
switch(ch)
{
case '/' : return 4;
case '*' : return 4;
case '+' : return 3;
case '-' : return 3;
default : return 0;
}
}
char pop() //function to pop the element from the stack
{
char ret;
if(top!=-1)
{ ret =stack[top];
top--;
return ret;
}
else
return '#';
}
char topelement() // function to return top element from the stack without popping
{
char ch;
if(top!=-1)
ch=stack[top];
else
ch='#';
return ch;
}
void push(char ch) // function to push an element in the stack
{
if(top!=size-1)
{
top++;
stack[top]= ch;
}
} |
|
|
|
|
|
|
|

楼主 |
发表于 2-1-2007 10:19 AM
|
显示全部楼层

edit 布道我. 不知道除了什么问题 |
|
|
|
|
|
|
| |
本周最热论坛帖子
|