I edited the code now the third case is also showing properly:
Very much thanks for pointing out the weird thing about my output.
I could not understand what you wanted to say in :
I have updated the code. Can you kindly check it out.
// to find the Reverse Polish Notation of an expression
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define max 400 //represents the length
void pop(char *stack, char *queue, int **top2, int **q2) {
queue[**q2] = stack[**top2];
**q2 += 1; //incresing the queue level count
**top2 -= 1; //reducing the top level
}
void operator(char *stack, char *queue, int *top1, int *q1, char op) {
if(op=='+') {
while(stack[*top1] == '/' || stack[*top1] == '*' || stack[*top1] == '-' || stack[*top1] == '^') {
pop(stack,queue,&top1,&q1);
}
}
else if(op=='-') {
while(stack[*top1] == '/' || stack[*top1] == '*' || stack[*top1] == '^') {
pop(stack,queue,&top1,&q1);
}
}
else if(op=='*') {
while(stack[*top1] == '/' || stack[*top1] == '^') {
pop(stack,queue,&top1,&q1);
}
}
else if(op=='/') {
while(stack[*top1] == '^') {
pop(stack,queue,&top1,&q1);
}
}
}
void push(char *stack, int *top1, char op) {
*top1 += 1;
stack[*top1] = op;
}
void pop_del(char *stack, int **top2) {
**top2 -= 1;
}
void right_bracket(char *stack, char *queue, int *top1, int *q1) {
while(stack[*top1] != '(')
pop(stack,queue,&top1,&q1); //here we pop the operators from the stack to the queue
pop_del(stack,&top1); //here we pop the '(' and discard it
}
void last_pop(char *stack, char *queue, int *top1, int *q1 ) {
while(*top1 > -1) {
queue[*q1] = stack[*top1];
*q1 += 1;
*top1 -= 1;
}
}
void print_queue(char *queue, int *q1) {
int loop1;
for(loop1=0;loop1<*q1;loop1++) {
printf("%c",queue[loop1]);
}
printf("\n");
//printf("%s\n",queue );
}
void operate(char *stack, char *queue, char *exp, int size) {
int loop1,top=-1,q_count=0;
for(loop1=0;loop1<size;loop1++){ //reading the tokens
if((exp[loop1]>='a' && exp[loop1]<= 'z') || (exp[loop1]>='A' && exp[loop1]<= 'Z')){
queue[q_count] = exp[loop1];
q_count++;
}
else if(exp[loop1] == '+' || exp[loop1] == '*' || exp[loop1] == '/' || exp[loop1] == '^' || exp[loop1] == '-') {
operator(stack,queue,&top,&q_count,exp[loop1]);
push(stack,&top,exp[loop1]);
}
else if(exp[loop1] == '(') {
push(stack,&top,exp[loop1]);
}
else if(exp[loop1] == ')') {
right_bracket(stack,queue,&top,&q_count);
}
}
last_pop(stack,queue,&top,&q_count);
print_queue(queue,&q_count);
}
int main() {
int t,loop1; //testcases
scanf("%d",&t);
char exp[t][max];
for(loop1=0;loop1<t && t<=100;loop1++) {
scanf("%s",exp[loop1]);
//printf("%ld\n",strlen(exp[loop1]));
//printf("%s\n", exp[loop1]);
}
printf("\n");
for(loop1=0;loop1<t && t<=100;loop1++) {
int loop2,c_size = strlen(exp[loop1]);
char *c_queue, *c_stack;
c_stack = (char*)malloc(sizeof(char)*c_size); //this allocates the stack
c_queue = (char*)malloc(sizeof(char)*c_size); //this allocates the queue
operate(c_stack,c_queue,exp[loop1],c_size);
free(c_stack);
free(c_queue);
}
return 0;
}