Description
一个四则运算算术表达式以有向无环图的邻接表方式存储,每个操作数原子都由单个字母表示。编写程序输出其逆波兰表达式。
Input
输入四则运算算术表达式。
Output
输出其逆波兰表达式。
-
Sample Input
(a+b)*c
-
Sample Output
ab+c*
这个题要求是用有向无环图,老师说可以不用,我就没用~
前面写的那个逆波兰代码大概是有点问题,过不了这道题,所以改了一下……
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct Stack{
char data;
struct Stack *next;
struct Stack *top;
struct Stack *bottom;
}Stack;
Stack *create()
{
Stack *q=(Stack *)malloc(sizeof(Stack));
q->bottom = (Stack*) malloc (sizeof(Stack));
q->bottom->next = NULL;
q->top = q->bottom;
return q;
}
char getTop(Stack *s)
{
return s->top->data;
}
void pop(Stack *s)
{
Stack *q=s->top;
s->top=s->top->next;
free(q);
}
void push(Stack *s,char b){
Stack *q=(Stack *)malloc(sizeof(Stack));
q->data=b;
q->next=s->top;
s->top=q;
}
int judge(char a, char b){
if((a == '*' && (b == '+' || b == '-')) || (a == '/' && (b == '+' || b == '-')))
return 1;
else
return 0;
}
int main()
{
char str[205];
char ans[205];
scanf("%s",&str);
int i;
Stack *s=create();
int s1=strlen(str);
for(i=0;i<s1;i++)
{
if(str[i]>='a'&&str[i]<='z')
{
printf("%c",str[i]);
}
else if(str[i]=='(')
{
push(s,str[i]);
}
else if(str[i]==')')
{
char top = getTop(s);
while(top != '(')
{
printf("%c",top);
pop(s);
top = getTop(s);
}
pop(s);
}
else
{
while(1)
{
char top = getTop(s);
if(judge(str[i], top) || s->top == s->bottom || top == '(')
{
push(s, str[i]);
break;
}
else if(top == '+' || top == '-' || top == '*' || top == '/')
{
printf("%c",top);
pop(s);
}
else
{
break;
}
}
}
}
while(s->top != s->bottom)
{
char top = getTop(s);
printf("%c",top);
pop(s);
}
printf("\n");
return 0;
}
尝试了一下没有栈底指针,程序出了bug……栈底指针还是很好用的