0% found this document useful (0 votes)
2 views

Lab04

The document outlines Lab 4 for a Data Structures and Algorithms course, focusing on implementing stacks in C++. It includes two main tasks: checking for balanced braces in C++ code using a stack, and evaluating postfix expressions with a stack-based calculator. Each task provides sample runs and incomplete source code for students to complete.

Uploaded by

Weishan Ooi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Lab04

The document outlines Lab 4 for a Data Structures and Algorithms course, focusing on implementing stacks in C++. It includes two main tasks: checking for balanced braces in C++ code using a stack, and evaluating postfix expressions with a stack-based calculator. Each task provides sample runs and incomplete source code for students to complete.

Uploaded by

Weishan Ooi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 7

TDS2111 Data Structures and Algorithms 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”

Question 1: Checking for Balanced Braces


C++ uses curly braces, “{” and “}”, to delimit groups of statements. For example, braces
begin and end a method’s body. If you treat a C++ programs as a string of characters, you
can use a stack to verify that a program contains balanced braces.

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

Incomplete Q1.cpp source code:

#include <iostream>
#include <string>
#include <stack>

using namespace std;

typedef char StackItemType;

class Stack {

private:
stack<StackItemType> s;

public:
bool isEmpty() const {
return s.empty();
}

void push(const StackItemType & v) {


s.push(v);
}
TDS2111 Data Structures and Algorithms Lab04

void pop() {
s.pop();
}

void pop(StackItemType & stackTop) {


stackTop = s.top();
s.pop();
}

void getTop(StackItemType & stackTop) {


stackTop = s.top();
}

int size() {
return s.size();
}
};

// TODO: Write your code here


// Begin Question
bool balancedBraces(const string & input)
{

}
// End Question

int main(int argc, char* argv[])


{
string input;
bool balancedSoFar = false;

cout << "Input a string: ";


cin >> input;

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

Question 2: Evaluating Postfix Expressions


Some calculators require you to enter postfix expressions. Recall that an operator in a
postfix expression applies to the two operands that immediately precede it. Thus, the
calculator must be able to retrieve the operands entered most recently. The ADT stack
provides this capability. In fact, each time you enter an operand, the calculator pushes it
onto a stack. When you enter an operator, the calculator applies it to the top two operands
on the stack, pops the operands from the stack, and pushes the result of the operation onto
the stack. The final result will be on the top of the stack.

Use the pseudocode algorithm given below to evaluate postfix expressions. Use only the
operators +, –, *, and /. Assume that the postfix expressions are syntactically correct.

for (each character ch in the string) {


if (ch is an operand)
Push value that operand ch represents onto stack
else { // ch is an operator named op
// evaluate and push the result
operand2 = top of stack
Pop the stack
operand1 = top of stack
Pop the stack
result = operand1 op operand2
Push result onto stack
}
}

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

Incomplete Q2.cpp source code:

/** ADT Stack - Pointer-based implementation. */

#include <iostream>
#include <stdexcept> // for exception
#include <string>
#include <cstddef> // for NULL
#include <new> // for bad_alloc

using namespace std;

typedef float StackItemType;

/** @class StackException


* Exception class throw by ADT stack. */
class StackException : public logic_error
{
public:
StackException(const string& message = "")
: logic_error(message.c_str())
{}
};

class Stack
{
public:

/** Default constructor. */


Stack();

/** Copy constructor.


* @param aStack The stack to copy. */
Stack(const Stack& aStack);

/** 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

/** Pointer to first node in the stack. */


StackNode *topPtr;
};

Stack::Stack() : topPtr(NULL)
{
}

// Copy constructor, Deep copy


Stack::Stack(const Stack& aStack)
{
if (aStack.topPtr == NULL)
topPtr = NULL; // original list is empty

else
{
// copy first node
topPtr = new StackNode;
topPtr->item = aStack.topPtr->item;

// copy rest of list


StackNode *newPtr = topPtr; // new node pointer
for (StackNode *origPtr = aStack.topPtr->next;
origPtr != NULL; origPtr = origPtr->next)
{
newPtr->next = new StackNode;
newPtr = newPtr->next;
newPtr->item = origPtr->item;
}

newPtr->next = NULL; //tail


}
}

Stack::~Stack()
{
// pop until stack is empty
while (!isEmpty())
pop();
// Assertion: topPtr == NULL
}

bool Stack::isEmpty() const


{
return topPtr == NULL;
}

void Stack::push(const StackItemType& newItem) throw(StackException)


{
// create a new node
try
{
StackNode *newPtr = new StackNode;

// set data portion of new node


newPtr->item = newItem;
TDS2111 Data Structures and Algorithms Lab04

// insert the new node


newPtr->next = topPtr; //newPtr->next pointer points to topPtr
topPtr = newPtr;
}
catch (bad_alloc e)
{
throw StackException(
"StackException: push cannot allocate memory.");
}
}

void Stack::pop() throw(StackException)


{
if (isEmpty())
throw StackException("StackException: stack empty on pop");
else
{
// stack is not empty; delete top
StackNode *temp = topPtr;
topPtr = topPtr->next;
// return deleted node to system
temp->next = NULL; // safeguard, don't point anything, points
to nothing
delete temp;
}
}

void Stack::pop(StackItemType& stackTop) throw(StackException)


{
if (isEmpty())
throw StackException("StackException: stack empty on pop");
else
{
// stack is not empty; retrieve and delete top
stackTop = topPtr->item;
StackNode *temp = topPtr;
topPtr = topPtr->next;

// return deleted node to system


temp->next = NULL; // safeguard, points to nothing
delete temp;
}
}

void Stack::getTop(StackItemType& stackTop) const throw(StackException)


{
if (isEmpty())
throw StackException("StackException: stack empty on getTop");
else
// stack is not empty; retrieve top
stackTop = topPtr->item;
}
TDS2111 Data Structures and Algorithms Lab04

// TODO: Write your code here


// Begin Question
float evalPostfixExpression (string str)
{

}
// End Question

int main()
{
system("title ADT Stack Application - Evaluating Postfix
Expressions");

string postfixExp;
float result;

cout << "Enter a postfix expression to be evaluated: ";


getline(cin, postfixExp);

result = evalPostfixExpression (postfixExp);

cout << postfixExp << " = " << result << endl;

system("pause");
return 0;
}

You might also like