[英]infix to postfix with white space
我有一個將中綴形式轉換為后綴形式的程序。 示例,如果輸入為: (-2+4-(3+3))
則輸出為: 2-4+33+-
我的預期輸出是:2-4-3 2 - 4 + 3 3 + -
我應該如何更改,當我pop()堆棧時,我在想多1個額外的空間。 這是代碼:
#include <stdio.h>
#include <ctype.h>
#include<string.h>
#define SIZE 50
char s[SIZE];
int top = -1;
void push(char elem) {
s[++top] = elem;
}
char pop() {
return (s[top--]);
}
int pr(char elem) {
switch (elem) {
case '#':
return 0;
case '(':
return 1;
case '+':
case '-':
return 2;
case '*':
case '/':
return 3;
}
}
int main()
{
char infx[50], pofx[50], ch, elem;
int i = 0, k = 0;
printf("\n\nRead the Infix Expression ?");
scanf("%s", infx);
push('#');
while ((ch = infx[i++]) != '\0') {
if (ch=='(')
push(ch);
else if (isalnum(ch))
pofx[k++] = ch;
else if (ch == ')') {
while (s[top] != '(')
pofx[k++] = pop();
elem = pop();
} else {
while (pr(s[top]) >= pr(ch))
pofx[k++] = pop();
push(ch);
}
}
while (s[top] != '#')
pofx[k++] = pop();
pofx[k] = '\0';
printf("\n\nGiven Infix Expn: %s Postfix Expn: %s \n", infx,pofx);
}
謝謝
首先,由於這一行,我無法編譯您的代碼
int top = -1;
void push(char elem) {
s[++top] = elem;
}
使用負數來初始化數組非常危險。 當我們轉到數組中的字符符號pop()
,它將在top = -1
處返回其初始狀態,這將導致編譯錯誤。 我的建議是將您的代碼更改為類似這樣的內容,這將導致您通過在數組中放置字符來更改某些內容:
int top = 0;
void push(char elem) {
s[top++] = elem;
}
至於在每個字符之間留有空格的字符串打印,請使用以下內容:
for (int i = 0, i < stren(infix) + 1; i++)
{
printf ("%c ", infix[i]);
}
// Same goes for the postfix. More of a formatting of the print characters really...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.