Prefix to Postfix program in C

Previous
Next
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct node
{
	char c;
	struct node *left;
	struct node *right;	
};
struct node *stk[20], *temp, *root;

char prefix[20],ch;
int top=-1, max=20, len;

void post(struct node*);
void exptree();
void push(struct node*);
struct node* pop();

int main()
{
	printf("Enter Prefix expression : ");
	scanf("%s", prefix);
	
	exptree();
	
	printf("Postfix expression is : ");
	post(root);
	return 0;
}

void post(struct node *p)
{
	if(p != NULL)
	{
		post(p->left);
		post(p->right);
		printf("%c", p->c);
	}
}

void exptree()
{
	int i;
	len = strlen(prefix);
	i=len-1;
	
	while(i>=0)
	{
		switch(prefix[i])
		{
			case '+' :
			case '-' :
			case '*' :
			case '/' :
			case '%' : 	temp = (struct node*)malloc(sizeof(struct node));
					   	temp->c = prefix[i];
				   		temp->left = pop();
				   		temp->right = pop();
				   		push(temp);
				   		break;
 		
 			default :	temp = (struct node*)malloc(sizeof(struct node));
 						temp->c = prefix[i];
 						temp->left = NULL;
 						temp->right = NULL;
 						push(temp);
 						break;
		}
		--i;
	}
	root = pop();
}

void push(struct node *p)
{
	if(top==max)
		printf("Stack is Full \n");
	else
		stk[++top] = p;
}

struct node* pop()
{
	if(top==-1)
		printf("Invalid expression \n");
	else
		return stk[top--];
}
Previous
Next

Add Comment

Courses Enquiry Form