Lab04
Lab04
Lab 4
Stacks
“It’s actually quite simple. View the stack as a stack of books from which there is one
way to add and one way to remove. -- Computer Scientist”
Task:
Implement the balanced braces checker by filling out the empty method.
Sample Run 1:
Input a string: abc{defg{ijk}{l{mn}}op}qr
Result: The above string is balanced
Sample Run 2:
Input a string: abc{def}}{ghij{kl}m
Result: The above string is not balanced
#include <iostream>
#include <string>
#include <stack>
class Stack {
private:
stack<StackItemType> s;
public:
bool isEmpty() const {
return s.empty();
}
void pop() {
s.pop();
}
int size() {
return s.size();
}
};
}
// End Question
balancedSoFar = balancedBraces(input);
if (balancedSoFar)
{
cout << "Result: The above string is balanced" << endl;
}
else {
cout << "Result: The above string is not balanced" << endl;
}
system("PAUSE");
return 0;
}
TDS2111 Data Structures and Algorithms Lab04
Use the pseudocode algorithm given below to evaluate postfix expressions. Use only the
operators +, –, *, and /. Assume that the postfix expressions are syntactically correct.
Task:
Implement the calculator that evaluates a postfix expression by filling out the empty
method. Make sure your method can process any number of digits from an integer.
Sample Run 1:
Enter a postfix expression to be evaluated: 2 10 100 / * 1000 +
2 10 100 / * 1000 + = 1000.2
Sample Run 2:
Enter a postfix expression to be evaluated: 2 3 4 + *
2 3 4 + * = 14
Sample Run 3:
Enter a postfix expression to be evaluated: 2 9 2 / * 8 + 7 - 4 /
2 9 2 / * 8 + 7 - 4 / = 2.5
TDS2111 Data Structures and Algorithms Lab04
#include <iostream>
#include <stdexcept> // for exception
#include <string>
#include <cstddef> // for NULL
#include <new> // for bad_alloc
class Stack
{
public:
/** Destructor. */
~Stack();
// Stack operations:
bool isEmpty() const;
void push(const StackItemType& newItem) throw(StackException);
void pop() throw(StackException);
void pop(StackItemType& stackTop) throw(StackException);
void getTop(StackItemType& stackTop) const throw(StackException);
private:
/** A node on the stack. */
struct StackNode
{
/** A data item on the stack. */
StackItemType item;
/** Pointer to next node. */
StackNode *next;
};
TDS2111 Data Structures and Algorithms Lab04
Stack::Stack() : topPtr(NULL)
{
}
else
{
// copy first node
topPtr = new StackNode;
topPtr->item = aStack.topPtr->item;
Stack::~Stack()
{
// pop until stack is empty
while (!isEmpty())
pop();
// Assertion: topPtr == NULL
}
}
// End Question
int main()
{
system("title ADT Stack Application - Evaluating Postfix
Expressions");
string postfixExp;
float result;
cout << postfixExp << " = " << result << endl;
system("pause");
return 0;
}