I need to implement a stack and this is what I have so far. After that I need to
ID: 3683252 • Letter: I
Question
I need to implement a stack and this is what I have so far.
After that I need to write a program called infixconverter that takes in a string containing an infix expression including (,), +, -, * and the integers and then outputs the postfix expression. I need to use the stack class for this as well.
public Stack(int c)
{
size = c;
stackArray = new long[size];
top = -1;
}
public boolean isEmpty()
{
return (top == -1);
}
public long pop()
{
return stackArray[top--];
}
public long top()
{
return stackArray[top];
}
public void push(long j)
{
stackArray[top++] = j;
}
//You are welcome to add any other private functions.
}
Explanation / Answer
#include <stdio.h>
#include <ctype.h>
#define MAX 100
typedef struct stack
{
int data[MAX];
int top;
}stack;
int priority(char);
void init(stack *);
int empty(stack *);
int full(stack *);
char pop(stack *);
void push(stack *,char);
char top(stack *);
void main()
{
stack s;
char x;
int token;
init(&s);
printf(" Enter infix expression:");
while((token=getchar())!=' ')
{
if(isalnum(token))
printf("%c",token);
else
if(token == '(')
push(&s,'(');
else
{
if(token == ')')
while((x=pop(&s))!='(')
printf("%c",x);
else
{
while(priority(token) <= priority(top(&s)) && !empty(&s))
{
x=pop(&s);
printf("%c",x);
}
push(&s,token);
}
}
}
while(!empty(&s))
{
x=pop(&s);
printf("%c",x);
}
printf(" ");
}
//---------------------------------------------
int priority(char x)
{
if(x == '(')
return(0);
if(x == '+' || x == '-')
return(1);
if(x == '*' || x == '/' || x == '%')
return(2);
return(3);
}
//---------------------------------------------
void init(stack *s)
{
s->top=-1;
}
//---------------------------------------------
int empty(stack *s)
{
if(s->top==-1)
return(1);
else
return(0);
}
//---------------------------------------------
int full(stack *s)
{
if(s->top==MAX-1)
return(1);
else
return(0);
}
//---------------------------------------------
void push(stack *s,char x)
{
s->top=s->top+1;
s->data[s->top]=x;
}
//---------------------------------------------
char pop(stack *s)
{
int x;
x=s->data[s->top];
s->top=s->top-1;
return(x);
}
//---------------------------------------------
char top(stack * s)
{
return(s->data[s->top]);
}
//---------------------------------------------