Re: [問題] 資料結構-用c語言array寫stack,push和 …

看板C_and_CPP (C/C++)作者 (十三)時間16年前 (2009/04/10 02:28), 編輯推噓2(202)
留言4則, 1人參與, 最新討論串5/5 (看更多)
我把所有break用/**/註解起來就是讓你知道為什麼程式會跳出 我只就語法修改, 簡單地算式應該可以對, 複雜的可能還要再debug #include<stdio.h> #include<string.h> #include<ctype.h> #include <stdlib.h> 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; char token; int y; S.top=0; printf("請輸入中序式, 例如 (a+b)*c-d/e :\n"); scanf("%s",infix); //----開始進行轉換為postfix的動作 //think:將掃的字元分為符號和字母,依括號法字母直接掃入新的array //運算子-符號則分為( ) + - * / ,左括號一律掃入,直到有右括號對應 " * / " 的優先權大於" + - " while(infix[i] != '\0') { token=infix[i++]; if( (token) >='a' && (token)<='z') { postfix[j++] = token; } else {//為符號-分為6種情況 if(token==')') {//右括號,遇到要把到左括號之前的全部POP出 並除去左括號 pop(&y); while(S.top > 0 && y != '(') { postfix[j++]=y; pop(&y); }//y不等於左括號,印出y push(y); push(token); /*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(&y); while(S.top > 0 && (y == '*' || y == '/' || y=='+' || y=='-')) {//y是優先權<=的情況 postfix[j++]=y; pop(&y); }//end while push(y); push(token); /*break;*/ } }//end case '+' else if( token=='-') {//case '-' if( S.top==0 || S.item[S.top]=='(') push(token); else { pop(&y); while(S.top > 0 && (y == '*' || y == '/' || y=='+' || y=='-')) {//y是優先權<=的情況 postfix[j++]=y; pop(&y); }//end while push(y); push(token); /*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(&y); while(S.top > 0 && (y == '*' || y == '/')) { postfix[j++]=y; pop(&y); } push(y); push(token); /*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(&y); while(S.top > 0 && (y == '*' || y == '/')) { postfix[j++]=y; pop(&y); } push(y); push(token); /*break;*/ } }//end case '/' }//end else 符號 }//end 掃入工作 while(S.top > 0) {//當掃入完成後清空stack pop(&y); postfix[j++]=y; } postfix[j] = '\0'; for(i=0;postfix[i]!='\0';i++) printf("%c",postfix[i]); printf("\n"); system("PAUSE"); return 0; }//end main void push(char x){ if (S.top<1000){ S.top++; S.item[S.top]=x;} } void pop(int *y){ if (S.top > 0){ *y=S.item[S.top]; S.top--;} } -- World of bleed1979 http://bleed1979.myweb.hinet.net/ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 118.168.133.22

04/11 20:26, , 1F
後來發覺是pop的地方要加一個假如不成立該如何的條件
04/11 20:26, 1F

04/11 20:27, , 2F
不給條件回傳的就是跳出
04/11 20:27, 2F

04/11 20:27, , 3F
break;是別的語言的寫法...如果用c寫應該加一個push才對
04/11 20:27, 3F

04/11 20:36, , 4F
謝謝你的幫忙...
04/11 20:36, 4F
文章代碼(AID): #19tZu_I- (C_and_CPP)
文章代碼(AID): #19tZu_I- (C_and_CPP)