Time Limit: 3000ms, Memory Limit: 10000KB , Accepted: 277, Total Submissions: 763
Description
假設表達式由單字母變量和雙目四則運算算符構成。試編寫程序,將一個通常書寫形式且書寫正確的表達式轉換爲逆波蘭式。
Input
輸入由單字母變量和雙目四則運算算符構成的表達式。
Output
輸出其逆波蘭式。
- Sample Input
(a+b)*c
- Sample Output
ab+c*
#include<stdio.h> #include<stdlib.h> typedef struct stack{ struct stack *pop; struct stack *bottom; struct stack *next; char sign; }stack; void init(stack *list){ list->bottom = (stack*) malloc (sizeof(stack)); list->bottom->next = NULL; list->pop = list->bottom; } void push(stack *list, char s){ stack *p; p = (stack*)malloc(sizeof(stack)); p->sign = s; p->next = list->pop; list->pop = p; } bool judge(char a, char b){ if((a == '*' && (b == '+' || b == '-')) || (a == '/' && (b == '+' || b == '-'))) return true; else return false; } void pop(stack *list){ stack *p; p = list->pop; list->pop = list->pop->next; free(p); } int main(){ char s,t; stack *list; list = (stack*) malloc (sizeof(stack)); init(list); while(scanf("%c",&s) && s!='\n'){ if(s >= 'a' && s <= 'z'){ printf("%c",s); } else if(s == '('){ push(list,s); } else if(s == ')'){ while(list->pop->sign != '('){ printf("%c",list->pop->sign); pop(list); } pop(list); } else{ while(1){ t=list->pop->sign; if(judge(s, list->pop->sign) || list->pop == list->bottom || list->pop->sign == '('){ push(list, s); break; } else if(t == '+' || t == '-' || t == '*' || t == '/'){ printf("%c",list->pop->sign); pop(list); } else{ break; } } } } while(list->pop != list->bottom){ printf("%c",list->pop->sign); pop(list); } printf("\n"); return 0; }
複習:
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
char data;
struct node *next;
}node, *pnode;
typedef struct stack{
struct node *bottom;
struct node *top;
}stack, *pstack;
void init(stack *list){
node *p = (pnode)malloc(sizeof(node));
p->data = '#';
p->next = NULL;
list->bottom = p;
list->top = p;
}
void push(stack *list, char x){
node *p = (pnode)malloc(sizeof(node));
p->data = x;
p->next = NULL;
list->top->next = p;
list->top = p;
}
bool isempty(stack *list){
if(list->top == list->bottom)
return true;
else
return false;
}
void pop(stack *list){
pnode p, q;
p = list->top;
q = list->bottom;
while(q->next != p)
q = q->next;
list->top = q;
free(p);
}
bool judgelow(pstack list, char x){
char y;
y = list->top->data;
if((x == '*' ||x == '/') && (y == '+' || y =='-'))
return false;
else
return true;
}
int main(){
char s;
pstack list = (pstack)malloc(sizeof(stack));
pnode p;
init(list);
while(scanf("%c", &s)){
if(s == '\n')
break;
else if(s >= 'a' && s <= 'z')
printf("%c", s);
else if(s == '(')
push(list, s);
else if(s == ')'){
while(list->top->data != '('){
printf("%c", list->top->data);
pop(list);
}
pop(list);
}
else{
while(1){
if(!judgelow(list, s) || isempty(list) || list->top->data == '('){
push(list, s);
break;
}
else{
printf("%c", list->top->data);
pop(list);
}
}
}
}
while(!isempty(list)){
printf("%c", list->top->data);
pop(list);
}
return 0;
}