C++ implement a program that can input an expression in postfix notation and out
ID: 3885660 • Letter: C
Question
C++ implement a program that can input an expression in postfix notation and output its value.
A SIMPLE STACK CLASS
main.cpp
/*******************************
* Week 2 lesson: *
* a simple Stack class *
*******************************/
#include
#include "stack.h"
using namespace std;
int main()
{
Stack s;
cout << "Insertion of 10 characters in s" << endl;
for (int i = 0; i < s.getSize(); i++)
{
char x = 32 + rand()%95;
cout << x << endl;
s.push(x);
}
cout << endl
<< "Displaying and deleting elements from s" << endl;
while(!s.isEmpty())
{
cout << "Item at the top: " << s.peek() << endl;
s.pop();
}
return 0;
}
Stack.cpp
/*******************************
* Week 2 lesson: *
* a simple Stack class *
*******************************/
#include "Stack.h"
/*
* Constructor. Initializes the stack.
*/
Stack::Stack()
{
top = 0;
}
/*
* Determines whether the stack is empty.
*
* Returns true if the stack is empty, false otherwise.
*/
bool Stack::isEmpty()
{
return top == 0;
}
/*
* Adds an element to the top of the stack.
*
* x: element to be added to the stack.
*/
void Stack::push(char x)
{
list[top] = x;
top++;
}
/*
* Removes the element at the top of the stack.
*/
void Stack::pop()
{
top--;
}
/*
* Returns the element at the top of the stack. Does not remove it.
*/
char Stack::peek()
{
return list[top-1];
}
/*
* Returns the size of the stack.
*/
int Stack::getSize()
{
return SIZE;
}
Stack.h
/*******************************
* Week 2 lesson: *
* a simple Stack class *
*******************************/
/*
* Class implementing a Stack ADT.
*/
class Stack
{
public:
Stack();
bool isEmpty();
void push(char);
void pop();
char peek();
int getSize();
private:
static const int SIZE = 10; //size of the queue array
char list[SIZE]; //array to store the stack items
int top; //amount of elements in the array
};
Explanation / Answer
#include<iostream>
#include "stack.h"
using namespace std;
int postfixEval(const char *postfix) {
Stack s;
int i = 0, a, b, results;
while(postfix[i] != '') {
if(postfix[i] >= '0' && postfix[i] <= '9')
s.push(postfix[i] - '0');
else
if (postfix[i] == '+') {
b = s.peek();
s.pop();
a = s.peek();
s.pop();
s.push(a + b);
}
else if (postfix[i] == '-') {
b = s.peek();
s.pop();
a = s.peek();
s.pop();
s.push(a - b);
}
else if (postfix[i] == '*') {
b = s.peek();
s.pop();
a = s.peek();
s.pop();
s.push(a * b);
}
else if (postfix[i] == '/') {
b = s.peek();
s.pop();
a = s.peek();
s.pop();
s.push(a / b);
}
i++;
}
return s.peek();
}
int main() {
string s;
cout << "Enter postfix expression: ";
cin >> s;
cout << "result: " << postfixEval(s.c_str()) << endl;
}
Input:
12+
output:
3
Input:
321+*
output:
9
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.