标签:技术 中缀 ack top main pac view void play
思路:
(1)先用堆栈将后缀表达式转化为表达式树,然后再将树进行中缀遍历,如果左右子树不为空就输出左右括号。
(2)后缀表达式转化为表达式树时要用堆栈进行:
如果是数字(字母)就入栈,如果是运算符就取堆栈的前两个节点,然后建立新的子树再将头结点入栈。
#include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> using namespace std; struct Node{ int x; struct Node *Left,*Right; }; typedef struct Node* Tree; struct N{ Tree x; struct N* next; }; typedef struct N* Stack; Stack CreateStack() { Stack S=(Stack)malloc(sizeof(struct N)); S->next=NULL; return S; } void Push(Tree x,Stack S) { Stack tp=(Stack)malloc(sizeof(struct N)); tp->x=x; tp->next=S->next; S->next=tp; } void Pop(Stack S) { Stack tp=S->next; S->next=tp->next; free(tp); } void PostOrder(Tree t) { if(t!=NULL) { PostOrder(t->Left); PostOrder(t->Right); printf("%c",t->x); } } void InOrder(Tree t) { if(t!=NULL) { if(t->Left!=NULL) printf("("); InOrder(t->Left); printf("%c",t->x); InOrder(t->Right); if(t->Right!=NULL) printf(")"); } } Tree Top(Stack S) { return S->next->x; } int main(void) { int len,n,i,x; Tree tp,p,h,t1,t2; Stack S=CreateStack(); char str[120]; gets(str); //printf("%s",str); len=strlen(str); for(i=0;i<len;i++) { Tree t=(Tree)malloc(sizeof(struct Node)); if(t==NULL) printf("Out of Space!!!\n"); t->x=str[i]; if(str[i]>=‘a‘&&str[i]<=‘z‘) { t->Left=NULL; t->Right=NULL; Push(t,S); } else { t1=Top(S); Pop(S); t2=Top(S); Pop(S); t->Left=t2; t->Right=t1; Push(t,S); } } tp=Top(S); Pop(S); InOrder(tp); //PostOrder(tp); return 0; } //ab+cde+**
标签:技术 中缀 ack top main pac view void play
原文地址:https://www.cnblogs.com/2018zxy/p/10043311.html