我正在寫一個基本程序,用於將中綴表示法中的表達式轉換爲使用堆棧的後綴表示法。中綴到Postfix轉換錯誤
這是我的程序。
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<string.h>
#define MAX_STACK_SIZE 100
//STACK IMPLEMENTATION BEGINS
struct stack{
int top;
char items[MAX_STACK_SIZE];
};
void push(struct stack* s, char n){
if(s->top==MAX_STACK_SIZE-1)
printf("Stack Overflow. Cannot push\n");
else
s->items[++s->top]=n;
}
bool isempty(struct stack* s){
if(size(s)==0)
return 1;
else return 0;
}
char pop(struct stack* s){
if(isempty(s))
{printf("\nStack Underflow. Cannot Pop\n");
return 0;}
else
{return (s->items[s->top--]);
}
}
bool isfull(struct stack* s){
if(size(s)==MAX_STACK_SIZE)
return 1;
else return 0;
}
void display(struct stack* s){
int num;
if(isempty(s))
printf("Stack empty. Nothing to display\n");
else
{
for(num=0;num<=s->top;num++)
printf("%d ",s->items[num]);
}
}
int size(struct stack* s){
if(s->top==-1)
return 0;
else
return (s->top+1);
}
//STACK IMPLEMENTATION ENDS
//checks if a character entered is an operator or not
bool isOperator(char ch){
if(ch=='-'||ch=='+'||ch=='*'||ch=='/')
return true;
else
return false;
}
//checks if a character entered is an operand(0-9) or not
bool isOperand(char ch){
if(ch>=48 && ch<=57)
return true;
else
return false;
}
//decides the precedence of operators
int precedence(char ch){
if(ch=='*'||ch=='/')
return 2;
if(ch=='+'||ch=='-')
return 1;
}
void main(){
/*
/*Declarations Begin*/
char infix_exp[50],ch;
int a;
struct stack s;
s.top=-1;
/*Declarations End*/
printf("Enter your infix expression\n");
scanf("%s",&infix_exp);
for(a=0;a<strlen(infix_exp);a++)//scanning the entire array
{
if(isOperator(infix_exp[a])){
while(s.top>=0 && isOperator(s.items[s.top]))
{
if(s.items[s.top]=='('|| isempty(&s))
{
push(&s,infix_exp[a]);
}
if(isOperator(s.items[s.top])){
while((s.top--)>=0){
if(precedence(infix_exp[a])>=precedence(s.items[s.top]))
{
ch=pop(&s);
printf("%c",ch);
push(&s,infix_exp[a]);
}
else
{
push(&s,infix_exp[a]);
}}}}}
if(isOperand(infix_exp[a])){printf("%c",infix_exp[a]);}
if(infix_exp[a]=='('){push(&s,'(');}
if(infix_exp[a]==')'){
while(s.top>=0 && s.items[s.top]!='(')
{
ch=pop(&s);
printf("%c",ch);
}
pop(&s);
}}}
這裏是輸出。
Enter your infix expression
6+1
61
RUN FINISHED; exit value 3; real time: 4s; user: 0ms; system: 0ms
我遵循的邏輯就是這樣。
用戶輸入他的表達式後,程序會掃描每個元素。 如果元素是一個操作數,它將被打印。 如果元素是開口支架,則將其推入堆棧。 如果元素是右括號,堆棧中的每個元素都會彈出並打印,直到遇到相應的左括號。 如果元素是操作者(通過isOperator()
功能檢查),那麼該堆棧的頂部元件可以是三個中的一個,
- 開括號-的元件被簡單地壓入堆棧;
- 空即堆棧爲空 - 元素簡單地推入堆棧;
- 另一個運算符 - 然後遍歷堆棧並且中綴表達式元素的優先級(
precedence()
)大於或等於堆棧頂部元素的優先級,那麼堆棧頂部被彈出並打印並且中綴表達式元素是推。否則,只有中綴表達式元素被推入,沒有東西被彈出。
我無法獲得輸出中的運算符。什麼可能是錯誤?我可能是一個微不足道的人,可能是打印價值觀,或者可能是我的邏輯。任何幫助讚賞。
size()函數中的'if'是多餘的。 – 2013-09-01 18:43:49
但這並不能解決問題。 – fts
這就是爲什麼我發佈它作爲評論而不是答案。 – 2013-09-01 18:54:27