Stack ADT: Data Structures and Algorithms Lab Journal - Lab 2
Stack ADT: Data Structures and Algorithms Lab Journal - Lab 2
Enrollment #: 01-235171-074
Objective
This lab is intended to introduce students to Stacks and their applications. The students will implement the
Stack and employ it in solving the given problems.
Stack ADT
Stack.h file
#define MAX_ITEMS 100
typedef char itemType;
class Stack{
public:
Stack();
int isFull();
int isEmpty() const;
void Push(itemType newItem);
void Pop(itemType& item);
void Display();
private:
int top;
itemType items[MAX_ITEMS];
};
int Stack::isFull()
{
return(top==MAX_ITEMS-1);
}
void Stack::Push(itemType newItem)
{
if(isFull())
{
cout<<"Stack Overflow"<<endl;
exit(1);
}
top++;
items[top]=newItem;
}
}
void Stack::Display()
{
if(isEmpty())
{
cout<<"Stack Underflow";
exit(1);
}
while(!isEmpty())
{
cout<<items[top];
top--;
}
}
Task 1 :
1. Show the contents of stack (at each step) once the following sequence of statements is
executed.
Stack S;
1. S.Push(‘A’); A
2. S.Push(‘B’); AB
3. S.Push(‘C’); ABC
4. S.Pop(); AB
5. S.Pop(); A
6. S.Push(‘D’); AD
7. S.Push(‘E’); ADE
8. S.Pop(); AD
9. S.Push(‘F’); ADF
10. S.Push(‘G’); ADFG
11. S.Pop(); ADF
12. S.Pop(); AD
2. Check the validity of parenthesis and show the contents of Stack and the output
expression at each step.
(A+B) *{ [ (C – D)+F*G]}
( (
+ (
{ {
[ {[
( {[(
- {[(
) {[
+ {[
* {[
] {
Task 2 :
Implement the Stack class and employ it to solve the given exercises.
Exercise 1
Write a C++ program that prompts user to enter a number (in decimal). Convert the number
into binary and display the binary number using the Stack.
CODE :
#include<iostream>
#include "stack.h"
#include<stdlib.h>
#include<string>
Write a program that reads a string (an array of characters) from a text file. Reverse the string
using the Stack and write the reversed string to another text file.
CODE :
#include<iostream>
#include "stack.h"
#include<stdlib.h>
#include<string>
#include<fstream>
data.open("text.txt", ios::in);
for (int i = 0; !data.eof(); i++)
{
data >> str[i];
s.Push(str[i]);
}
data.close();
data2.open("text2.txt", ios::out);
for (int i = 0; !s.isEmpty();i++)
{
s.Pop(st[i]);
data2 << st[i];
}
data2.close();
system("pause");
}
Exercise 3
Write a function that reads a Mathematical expression from a text file and verifies the validity of
parenthesis in the expression using a Stack.
CODE :
#include<iostream>
#include "stack.h"
#include<stdlib.h>
#include<string>
#include<fstream>
else
s.Pop(a);
}
}
if (s.isEmpty())
cout << "Expression is valid!" << endl;
else
cout << "Expression is not valid!:" << endl;
system("pause");
}
2. Exercise 2
3. Exercise 3
+++++++++++++++++++++++++