作者lovemost (最爱)
看板C_and_CPP
标题Re: [问题] 资料结构-用c语言array写stack,push和 …
时间Fri Apr 10 00:27:59 2009
#include<stdio.h>
#include<string.h>
#include<ctype.h>
//只能够计算加减乘除和左右括号的四则运算
//infix先转postfix再作计算
//使用方法array的stack
typedef struct STACK
{
char item [1000];
int top;
}STACK;
STACK S;
void push(char );
void pop(int *);
int main(){
char infix[1000];
char postfix[1000];
int i=0,j=0;
S.top=0;
printf("请输入中序式, 例如 (a+b)*c-d/e :\n");
scanf("%s",infix);
char token;
int y;
//----开始进行转换为postfix的动作
//think:将扫的字元分为符号和字母,依括号法字母直接扫入新的array
//运算子-符号则分为( ) + - * / ,左括号一律扫入,直到有右括号对应 " * / "
的优先权大於" + - "
while(infix[i] != '\0'){// 进行扫入的工作
token=infix[i++];
if( (token) >='a' && (token)<='z'){postfix[j++]=token;}//判断为字母
else{//为符号-分为6种情况
if(token==')'){//右括号,遇到要把到左括号之前的全部POP出 并除去左括号
pop(&(int)y);
while(y != '('){
postfix[j++]=y;
pop(&(int)y);}//y不等於左括号,印出y
break;
} //end ')'
else if( token=='(' ) push(token);//case '(' 在stack外优先权最高,stack内优先权最低
else if( token=='+'){//case '+' 优先权等於 + - 小於 * / 大於(
if( (S.top==0) || (S.item[S.top]=='(')) push(token);
else {pop(&(int)y);
while(y == '*' || y == '/' || y=='+' || y=='-'){//y是优先权<=
的情况
postfix[j++]=y;
pop(&(int)y);}//end while
break;
}}//end case '+'
else if( token=='-'){//case '-'
if( S.top==0 || S.item[S.top]=='(') push(token);
else {pop(&(int)y);
while(y == '*' || y == '/' || y=='+' || y=='-'){//y是优先权<=
的情况
postfix[j++]=y;
pop(&(int)y);}//end while
break;
}}//end case '-'
else if( token=='*'){//优先权等於 * / 大於( + -
if( S.top==0 || S.item[S.top]=='(' || S.item[S.top]=='+' ||
S.item[S.top]=='-') push(token);
else{pop(&(int)y);
while(y == '*' || y == '/'){
postfix[j++]=y;
pop(&(int)y);}
break;
}}//end case '*'
else { //token = '/'
if( S.top==0 || S.item[S.top]=='(' || S.item[S.top]=='+' ||
S.item[S.top]=='-') push(token);
else{pop(&(int)y);
while(y == '*' || y == '/'){
postfix[j++]=y;
pop(&(int)y);}
break;
}}//end case '/'
}//end else 符号
}//end 扫入工作
while(S.top > 0){//当扫入完成後清空stack
pop(&(int)y);
postfix[j]=y;
j++;}
for(i=0;postfix[i]!='\0';i++)
printf("%c",postfix[i]);
system("PAUSE");
return 0;
}//end main
void push(char x){
if (S.top<100){
S.top++;
S.item[S.top]=x;}
}
void pop(int *y){
if (S.top > 0){
*y=S.item[S.top];
S.top--;}
}
经过几次修改和精减变成这样...
可是程式转为postfix还是不对...
虽然pop和push的问题解决了...
不过目前还是不知道为甚麽跑一跑会自动跳出(没出现任何错误讯息)
当输入少的时候还是正确的ex:a+b*c
当输入一多就会跳出...也不会停在system("pause")的地方
不知道有没有高名的版友看的出是哪边出了问题....
(这种没任何讯息的找半天都还是不知道问题出在哪)
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 118.169.232.21
1F:→ tsaiminghan:你item设1000, pop那边别设100啊 04/10 00:33
2F:→ tsaiminghan:没全部看完,但是 04/10 00:42
3F:→ tsaiminghan:if( (S.top==0) || (S.item[S.top]=='(')) push(token 04/10 00:42
4F:→ tsaiminghan:这行就错了。S.top == 0时,这是empty stack 04/10 00:43
5F:→ tsaiminghan:啊,我看错了,你的top跟我的不一样.... 04/10 00:45
6F:→ tsaiminghan:…嗯,你的top==0的位完全不会用到。拿top==0的位置的 04/10 00:48
7F:→ tsaiminghan:资料去比对是错的 04/10 00:49
8F:→ tsaiminghan:啊,你用的是||,所以top==0没错,我上面写的不要看 04/10 00:51