//stack appliation ---expression convertion from infix to postfix
#include <stdio.h>
#include <stdlib.h> //include exit(),malloc() function。
#include <string.h> //include strlen function
#include <ctype.h>
#define EMTPTYSTACK -1 //define the empty stack arry subcript, so the element would be started from array[0]
#define MAXELEMENTS 100
struct StackRecord;
typedef struct StackRecord *Stack;
typedef char ElementType ; //define element type
void Error (char input[])
{
printf("%s\n",input);
exit(4);
}
struct StackRecord
{
int Capacity; // record the total space allocated for this stack
int TopOfStack; //record the Array subscript of top element
ElementType *Array; //record the allocated array address
};
int IsEmpty(Stack S);
int IsFull(Stack S);
void Push(ElementType x, Stack S);
void Pop(Stack S);
Stack CreateStack(int Maxelement);
void MakeEmpty (Stack S);
ElementType Top(Stack S);
ElementType PopAndTop(Stack S);
int IsEmpty (Stack S)
{
return S->TopOfStack == EMTPTYSTACK;
}
int IsFull (Stack S)
{
return S->TopOfStack == S->Capacity-1; //topofstack is ranged from 0 to MAXELEMENTS-1
}
void Push(ElementType x, Stack S)
{
if(IsFull(S))
Error("Out of Space !!!\n");
else
S->Array[ ++S->TopOfStack ] = x;
}
void Pop (Stack S)
{
if ( IsEmpty( S) )
Error("Empty Stack !!\n");
else
S->TopOfStack--;
}
Stack CreateStack (int Maxelement)
{
Stack S;
S = malloc(sizeof(struct StackRecord));
if (S == NULL)
Error("Out of Space !!!\n");
S->Array=malloc(sizeof(ElementType)*Maxelement);
if (S->Array == NULL)
Error("Out of Space !!!\n");
S->Capacity = Maxelement;
MakeEmpty (S);
return S;
}
void MakeEmpty (Stack S)
{
S->TopOfStack = EMTPTYSTACK;
}
ElementType Top(Stack S)
{
return S->Array[S->TopOfStack];
}
ElementType PopAndTop(Stack S)
{
return S->Array[S->TopOfStack--]; //operator precedence of -> (left to right) is higher than --/++ ;
}
int Getprecedence(char x)
{
if (x == '+' || x == '-')
return 1;
if (x == '*' || x == '/' )
return 2;
if (x == '(' || x == ')')
return 3;
return -1;
}
int ZeroIfNegative (int x)
{
if (x<0)
return 0;
else
return x;
}
int main (void)
{
char ch;
int stack_precedence;
int input_precedence;
Stack stack_instance;
stack_instance=CreateStack(MAXELEMENTS);
while( (ch=getchar()) != EOF && ch != 'q')
{
if( isdigit(ch) )
putchar(ch);
else
{
if ( IsEmpty(stack_instance) ) //push operator for empty stacks
Push(ch,stack_instance);
else
//{
//if ( Getprecedence (Top(stack_instance)) < Getprecedence(ch) )
//Push(ch, stack_instance);
//else
{ while( (Getprecedence (Top(stack_instance)) >= Getprecedence(ch) ) && (!IsEmpty(stack_instance)) )
//because addition/subtraction/multiplication/division are all associated from left to right,so it is >=,
//otherwise it will be > only.
{printf("%c",Top(stack_instance) );
Pop(stack_instance);
}
Push(ch,stack_instance);
}
putchar(' ') ;//to split the digits
}
}
while(! IsEmpty(stack_instance) )
{putchar(Top(stack_instance) );
Pop(stack_instance);
}
return 0;
}