In: Computer Science
Please code in C
/* Implements functions that operate on Stack
1. PUSH
2. POP
3. isEmpty
4. PEEK
5. Size
*/
#include <stdio.h>
#define CAPACITY 1000
//Two stacks .. for each stack we need
// 1. An Array that can hold capacity of elements
// 2. A top initialzied to -1 (signifying that the stak is empty at the start)
//NOTE : THESE STACKS ARE OF TYPE CHAR :( ... so you need to FIX IT!!!! to int and every function as well :((
char stack1[CAPACITY];
char stack2[CAPACITY];
int top1 = -1;
int top2 = -1;
int push(char stack[], int top, char data){
if(*top<CAPACITY-1){
*top += 1;
stack[*top] = data;
return 1;
}
return 0;
}
char pop(char stack[], int* top){
char c;
if(*top > -1){
c = stack[*top];
*top -=1;
}
return c;
}
char peek(char stack[], int* top){
char c = 0;
if(*top > -1){
c = stack[*top];
}
return c;
}
int isEmpty(char stack[],int* top){
if (*top == -1)
return 1;
return 0;
}
int size(char stack[],int* top){
return *top+1;
}
int main(){
//YOUR CODE HERE for REVESE POLISH NOTATION CALCULATION!
}
Here's a C Code for the question:
int stack1[CAPACITY];
int stack2[CAPACITY];
int top1 = -1;
int top2 = -1;
int push(int stack[], int top, int data){
if(*top<CAPACITY-1){
*top += 1;
stack[*top] = data;
return 1;
}
return 0;
}
int pop(int stack[], int* top){
int c;
if(*top > -1){
c = stack[*top];
*top -=1;
}
return c;
}
int peek(int stack[], int* top){
int c = 0;
if(*top > -1){
c = stack[*top];
}
return c;
}
int isEmpty(int stack[],int* top){
if (*top == -1)
return 1;
return 0;
}
int size(int stack[],int* top){
return *top+1;
}
int evaluateReversePolish(char *exp){
for (i = 0; exp[i]; i++)
{
// If the scanned character is an operand (number here),
// push it to the stack.
if (exp[i]>='0'&&exp[i]<='9')
push(stack1, exp[i] - '0');
// If the scanned character is an operator, pop two
// elements from stack apply the operator
else
{
int val1 = pop(stack1);
int val2 = pop(stack1);
switch (exp[i])
{
case '+': push(stack1, val2 + val1); break;
case '-': push(stack1, val2 - val1); break;
case '*': push(stack1, val2 * val1); break;
case '/': push(stack1, val2/val1); break;
}
}
}
return pop(stack1);
}