#include<stdio.h>
#include<stdlib.h>
typedef char Element;//
struct snode{
Element data;
struct snode* next;
};
typedef struct snode* Stack;
Stack createstack();//建立空栈
void push(Element item,Stack S);
int isempty(Stack S);
void pop(Stack S);
int compare(Element item,Element ch);
int sign=0;
int main(){
Stack L;
L=createstack();
Element ch;
int flag=1;
int fuhao=0;
while(1){
scanf("%c",&ch);
if(ch==')')sign=1;
if(ch=='\n')break;//
else if(ch>='0'&&ch<='9'){
if(flag==1)printf("%c",ch);
else printf(" %c",ch);
flag=0;
fuhao=1;
}
else if(fuhao==0){
printf("%c",ch);
}
else push(ch,L);
}
Stack p=L;
while(p->next !=NULL){////剩下的符号
printf(" %c",p->next->data );
p=p->next ;
}
}
Stack createstack(){
Stack S;
S=(Stack)malloc(sizeof(struct snode));
S->next =NULL;
return S;
}
int isempty(Stack S){
return (S->next ==NULL);
}
void push(Element item,Stack S){
while(sign==1){//遇到右括号打印括号里面的内容
pop(S);
if(S->next->data =='(' )break;
}
if(sign==1){
pop(S);
sign=0;
return ;
}
while(S->next !=NULL&&compare(S->next->data ,item)){//熔断
pop(S);
}
if(item!=')'){
Stack tmpcell;
tmpcell=(Stack)malloc(sizeof(struct snode));
tmpcell->data=item;
tmpcell->next=S->next;
S->next =tmpcell;
}
}
void pop(Stack S){
if(isempty(S))return;
struct snode* first;
Element ch;
first=S->next ;
S->next =first->next ;
ch=first->data ;
free(first);
if(ch!='('&&ch!=')')printf(" %c",ch);//左右括号不打印
}
int compare(Element top,Element ch){
if(ch=='('||top=='(')return 0;//算法
if(ch==')')return 1;
switch(ch){//1顶弹出
case '+':
case '-':
return 1;
case '*':
case '/':
switch(top){
case '*':
case '/':
return 1;
case '+':
case '-':
return 0;
}
}
}
感觉已经写的差不多了,输出结果似样例,为什么还是答案错误?还有嵌套括号处理的不对么?