#include <stdio.h>
#include <stdlib.h>
#include <Stack_Head.h>
#include <string.h>
/*
2018.4.4 栈的链表实现
*/
Stack Initial_Stack()
{
Stack S=(Stack)malloc(sizeof(struct Node));
S->Next=NULL;
return S;
}
int IsEmpty(Stack S)
{
return S->Next==NULL;
}
void Dispose_Stack(Stack S)
{
PtrToNode P=S->Next;
while(P!=NULL)
{
free(S);
S=P;
P=P->Next;
}
}
void Push(Stack S,ElementType x)
{
PtrToNode T=(PtrToNode)malloc(sizeof(struct Node));
T->x=x;
T->Next=S->Next;
S->Next=T;
}
void Pop(Stack S)
{
PtrToNode P;
if(!IsEmpty(S))
{
P=S->Next;
S->Next=P->Next;
}
free(P);
}
ElementType Top(Stack S)
{
PtrToNode P;
if(!IsEmpty(S))
{
P=S->Next;
return P->x;
}
else
printf("isempty!");
exit(0);
}
int priority(char oprd)
{
if (oprd=='(')
return 0;
if(oprd=='+'||oprd=='-')
return 1;
if(oprd=='*'||oprd=='/')
return 2;
}
void infix_to_post()
{
char c[100];
scanf("%s",c);
//Stack OPTR=Initial_Stack();// number
Stack OPRD=Initial_Stack();//operator
Push(OPRD,-1);
//printf("alreading push");
int i;
for(i=0;i<strlen(c);i++)
{
if(c[i]>='a'&&c[i]<='z')
{
printf("%c",c[i]);
}
else if(c[i]=='(') //注意 如果是左括号无条件压 相当于是最高优先级 但是POP的时候 当时是最低优先级 任何时候都不出 只有当前读的是右括号才出来
{
Push(OPRD,c[i]);
}
else if(c[i]==')')
{
while(Top(OPRD)!='(')
{
printf("%c", Top(OPRD));
Pop(OPRD);
}
Pop(OPRD);
}
else
{
//注意:只有当前的优先级大于栈顶优先级时才push 所以相等时 栈顶也要Pop出来
while(priority(c[i])<=priority(Top(OPRD)))
{
char oprd = Top(OPRD);
printf("%c",oprd);
Pop(OPRD);
}
Push(OPRD,c[i]);
//printf("alreading puch %c",c[i]);
}
}
while(!IsEmpty(OPRD))
{
printf("%c",Top(OPRD));
Pop(OPRD);
}
}
int main()
{
//printf("Hello world!\n");
/* Stack S=Initial_Stack();
Push(S,1);
Push(S,2);
Push(S,3);
printf("%d",Top(S));
*/
infix_to_post();
return 0;
}
头文件
#ifndef STACK_HEAD_H_INCLUDED
#define STACK_HEAD_H_INCLUDED
typedef struct Node *PtrToNode;
#define ElementType char
typedef struct Node *Stack;
int IsEmpty(Stack S);
Stack Initial_Stack();
void Dispose_Stack(Stack S);
void Push(Stack S , ElementType x);
void Pop(Stack S);
ElementType Top(Stack S);
#endif // STACK_HEAD_H_INCLUDED
struct Node{
ElementType x;
struct Node * Next;
};
样例:
a+b*c+(d*e+f)*g
abc*+de*f+g*+
Process returned 0 (0x0) execution time : 17.120 s
Press any key to continue.