aut-eng-2014/aut-eng-2014 — pull request #47 by mroxana (2014-10-29 16:40:36+00:00)
Title: 4.6.1

#include
#include
#include
#include

#define MAX 20
#define EMPTY -1

typedef struct node
{
int value;
struct node *left,*right;
}NodeT;

typedef struct stackk
{
struct node *data[MAX];
int top;
}StackT;

int isempty(StackT *s)
{
if(s->top == EMPTY)
return 1;
else
return 0;
}

void emptystack(StackT* s)
{
s->top=EMPTY;
}

void push(StackT* s, NodeT *node)
{
if(s->top == (MAX-1))
{
printf("\nSTACK FULL");
}
else
{
++s->top;
s->data[s->top]=node;
}
}

NodeT* pop(StackT* s)
{
NodeT *value=NULL;
if(isempty(s) != 1)
{
value= s->data[s->top];
--s->top;
}
return value;
}

void transformation(char* postfix, NodeT **root)
{
StackT S;
NodeT *newnode,*op1,*op2;
char *p;

p = &postfix[0];
emptystack(&S);

while(*p != '\0')
{
while(*p == ' ')
{
p++;
}
if(isalpha(*p) || isdigit(*p) || *p=='#')
{
newnode = (NodeT*)malloc(sizeof(NodeT));
newnode->value = *p;
newnode->left = NULL;
newnode->right = NULL;
push(&S,newnode);
}
else
{
op1 = pop(&S);
op2 = pop(&S);
newnode =(NodeT*)malloc(sizeof(NodeT));
newnode->value = *p;
newnode->left = op2;
newnode->right = op1;
push(&S,newnode);
}
p++;
}
*root = pop(&S);
}

void read(char *expression)
{
char ch;
FILE *f;
int i=0;
f = fopen("postfix_expression.txt","r");

if( f == NULL )
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}

while( ( ch = fgetc(f) ) != EOF )
{
expression[i]=ch;
i++;
}
expression[i]='\0';
printf("\n");
fclose(f);
}

void preorder(NodeT* root)
{
if(root == NULL)
return;
printf("%c",root->value);
preorder(root->left);
preorder(root->right);
}

void inorder(NodeT *root)
{
if(root == NULL)
return;
inorder(root->left);
printf("%c",root->value);
inorder(root->right);
}

void postorder(NodeT *root)
{
if(root == NULL)
return;
postorder(root->left);
postorder(root->right);
printf("%c",root->value);
}

int main()
{
char expression[20];
read(expression);

int i;
printf("The mathematical expression in postfix form is :\n" );
for(i=0;i