You are on page 1of 29

CSE225L – Data Structures a nd Alg o rithms Lab

Lab 01
Dynamic Memory Allocation

In this lab, we will learn how to allocate memory dynamically and de-allocate memory that is allocated dynamically.
Recall the syntax for the operators new and delete.

Pointer = new DataType;


Pointer = new DataType [IntExpression];

delete Pointer;
delete [] Pointer;

Example:
int *a = new int;
char *b = new char[5];
float *c = new float[3*someVariable+1];
double **d = new double*[10];
delete a;
delete [] b;
delete [] c;
delete [] d;

Before you begin: Create a C++ project. A project contains all the relevant files such as source codes, header files,
and relevant resources. Also, under CodeBlocks, you can only debug your program under a project; single-file
program debugging is not supported. Follow the steps below to create a project.
1. File ⇒ New ⇒ Project... ⇒ Console Application ⇒ Go.
2. The "Console Application" wizard appears:
a. Next
b. Select "C++" ⇒ Next.
c. In "Project Title", enter the name you want to assign to the project (for example lab01). In "Folder to
create project in", set to your working directory, (for example d:\labs). Accept the default for the rest ⇒
Next. A project directory "lab01" will be created under "d:\labs", with a project configuration filename
of "lab01.cbp". You could later create more projects under this working directory "d:\labs".
d. In "Compiler" field, accept the defaults of "GNU GCC Compiler" ⇒ Finish.
3. Under the "Management" pane ⇒ Choose "Projects" tab ⇒ Expand the project node "lab01" ⇒ Expand
"Sources" node ⇒ Double-click "main.cpp", which is an example program to print "Hello, world!".
4. To build the program, select "Build" menu ⇒ Build.
5. To run the program, select "Build" menu ⇒ Run.

Tasks:

Task 1: Using the new operator, allocate an integer array of user specified size (the user gives the size of the array as
input). Assign values to the array elements by taking user inputs and then print the values. Finally de-allocate the array
using the delete operator.

Task 2: Using the new operator, allocate a two dimensional character array. Again the number of rows and columns
are going to be provided by the user as input. All of the rows are the same size. Take character strings as input from
the user and then print the strings. Finally de-allocate the array using the delete operator.

Task 3: Using the new operator, allocate a two dimensional integer array. The number of rows and columns are going
to be provided by the user as input. However, in this task, all of the rows are not the same size (the array is uneven).
The user will specify how many elements the individual rows will have. Assign values to the array elements by taking
user inputs and then print the values. Finally de-allocate the array using the delete operator.
CSE225L – Data Structures a nd Alg o rithms Lab
Lab 02
Classes & Objects

Recall the class for dynamic array we developed in our 2nd lecture. In this lab session, you will implement and test that
class.

Before you begin: Create a C++ project. Then create a header file and a source file for your project. Follow the steps
below to create files.
1. Create a header file.
a. File ⇒ New ⇒ File. Select C/C++ header. Select Go ⇒ Next.
b. Click the browse button beside the textbox labelled “Filename with full path”. A window appears. In
the textbox labelled “File name”, type in the name you want to assign to the header file (in this case
dynarr.h). Select Save ⇒ select All ⇒ select Finish.
c. Under the "Management" pane ⇒ Choose "Projects" tab ⇒ Expand the project node ⇒ Expand
"Headers" node. You will see the file you just created. It is mostly blank except for a few lines of
code. It is time to add your own code to it. For your convenience, the content of this file is already
provided with this manual (refer to the table in the opposite page). Add the content of dynarr.h just
before the #endif statement.
2. Next, create the source file
a. File ⇒ New ⇒ File. Select C/C++ source. Select Go ⇒ Next.
b. Select "C++" ⇒ Next.
c. Click the browse button beside the textbox labelled “Filename with full path”. A window appears. In
the textbox labelled “File name”, type in the name you want to assign to the source file (in this case
dynarr.cpp). Select Save ⇒ select All ⇒ select Finish.
d. Under the "Management" pane ⇒ Choose "Projects" tab ⇒ Expand the project node ⇒ Expand
"Sources" node. You will see the file you just created. It is completely blank. It is time to add your
own code to it. For your convenience, the content of this file is already provided with this manual
(refer to the table in the opposite page). Add the content of dynarr.cpp to the newly created file.
3. In the opposite page, will find some tasks that you have to perform using the code provided. You have to
modify the file main.cpp and perform these task in that file.
4. To build the program, select "Build" menu ⇒ Build.
5. To run the program, select "Build" menu ⇒ Run.
dynarr.h dynarr.cpp

#ifndef DYNARR_H_INCLUDED #include "dynarr.h"


#define DYNARR_H_INCLUDED #include <iostream>
class dynArr using namespace std;
{
private: dynArr::dynArr()
int *data; {
int size; data = NULL;
public: size = 0;
dynArr(); }
dynArr(int); dynArr::dynArr(int s)
~dynArr(); {
void setValue(int, int); data = new int[s];
int getValue(int); size = s;
}; }
#endif // DYNARR_H_INCLUDED dynArr::~dynArr()
{
delete [] data;
}
int dynArr::getValue(int index)
{
return data[index];
}
void dynArr::setValue(int index, int value)
{
data[index] = value;
}

Tasks:

Task 1: In the driver file (main.cpp), perform the following sub-tasks.


1. Create two objects of this class, one with no constructor argument and one with the argument 5.
2. Take five input values from the user and store them in the array inside the second object using the set method.
3. For the second object, print all the values you just stored.
Note that, you cannot assign anything in the first object since the array inside it has size 0. Neither can you change
the size of this array to some other size.

Task 2: Modify the header and the source files. Add a member function void allocate(int s) which allows
you to change the size of the array. Make sure that memory is not leaked.

Task 3: Modify the header file and the source files again, so that it works for two dimensional array where all the
rows are the same size. The user will specify the number of rows and columns as well as the content of the array,
which you will take as input from user in the main function.
CSE225L – Data Structures and Algorithms Lab
Lab 03
Template Class and Operator Overloading

Task 1: Recall the class we used in the previous lab to allocate memory dynamically. Modify the header file
and the source file given below so that they now work as template class (the array elements in the
dynamically allocated memory can be any type as the user defines).
dynarr.h dynarr.cpp

#ifndef DYNARR_H_INCLUDED #include "dynarr.h"


#define DYNARR_H_INCLUDED #include <iostream>
using namespace std;
class dynArr
{ dynArr::dynArr(int s)
private: {
data = new int[s];
int *data; size = s;
int size; }
dynArr::~dynArr()
public: {
dynArr(int); delete [] data;
~dynArr(); }
void setValue(int, int); int dynArr::getValue(int index)
int getValue(int); {
}; return data[index];
}
#endif // DYNARR_H_INCLUDED void dynArr::setValue(int index, int value)
{
data[index] = value;
}

Task 2: Recall the complex number class we discussed in our lectures. Modify the class and overload the *
(multiplication) and the != (not equal) operators for the class given below.
complex.h complex.cpp

#ifndef COMPLEX_H_INCLUDED #include "complex.h"


#define COMPLEX_H_INCLUDED #include <iostream>
using namespace std;
class Complex
{ Complex::Complex()
public: {
Complex(); Real = 0;
Complex(double, double); Imaginary = 0;
Complex operator+(Complex); }
void Print(); Complex::Complex(double r, double i)
private: {
double Real, Imaginary; Real = r;
}; Imaginary = i;
}
#endif // COMPLEX_H_INCLUDED Complex Complex::operator+(Complex a)
{
Complex t;
t.Real = Real + a.Real;
t.Imaginary = Imaginary + a.Imaginary;
return t;
}
void Complex::Print()
{
cout << Real << endl;
cout << Imaginary << endl;
}
CSE225L – Data Structures a nd Alg o rithms Lab
Lab 04
Unsorted List (array based)

In today’s lab we will design and implement the List ADT where the items in the list are unsorted.

unsortedtype.h template <class ItemType>


void
#ifndef UNSORTEDTYPE_H_INCLUDED UnsortedType<ItemType>::RetrieveItem(ItemType&
#define UNSORTEDTYPE_H_INCLUDED item, bool &found)
{
const int MAX_ITEMS = 5; int location = 0;
bool moreToSearch = (location < length);
template <class ItemType> found = false;
class UnsortedType while (moreToSearch && !found)
{ {
public : if(item == info[location])
UnsortedType(); {
void MakeEmpty(); found = true;
bool IsFull(); item = info[location];
int LengthIs(); }
void InsertItem(ItemType); else
void DeleteItem(ItemType); {
void RetrieveItem(ItemType&, bool&); location++;
void ResetList(); moreToSearch = (location < length);
void GetNextItem(ItemType&); }
private: }
int length; }
ItemType info[MAX_ITEMS]; template <class ItemType>
int currentPos; void UnsortedType<ItemType>::InsertItem(ItemType
}; item)
#endif // UNSORTEDTYPE_H_INCLUDED {
info[length] = item;
unsortedtype.cpp length++;
}
#include "UnsortedType.h" template <class ItemType>
void UnsortedType<ItemType>::DeleteItem(ItemType
template <class ItemType> item)
UnsortedType<ItemType>::UnsortedType() {
{ int location = 0;
length = 0; while (item != info[location])
currentPos = -1; location++;
} info[location] = info[length - 1];
template <class ItemType> length--;
void UnsortedType<ItemType>::MakeEmpty() }
{
length = 0;
}
template <class ItemType>
bool UnsortedType<ItemType>::IsFull()
{
return (length == MAX_ITEMS);
}
template <class ItemType>
int UnsortedType<ItemType>::LengthIs()
{
return length;
}
template <class ItemType>
void UnsortedType<ItemType>::ResetList()
{
currentPos = -1;
}
template <class ItemType>
void
UnsortedType<ItemType>::GetNextItem(ItemType&
item)
{
currentPos++;
item = info [currentPos] ;
}
Generate the driver file (main.cpp) where you perform the following tasks. Note that you cannot make any change to
the header file or the source file.

Operation to Be Tested and Description of Action Input Values Expected Output


• Create a list of integers
•• Insert four items 5 7 6 9
• Print the list 5769
• Print the length of the list 4
• Insert one item 1
• Print the list 57691
• Retrieve 4 and print whether found or not Item is not found
• Retrieve 5 and print whether found or not Item is found
• Retrieve 9 and print whether found or not Item is found
• Retrieve 10 and print whether found or not Item is not found
• Print if the list is full or not List is full
• Delete 5
• Print if the list is full or not List is not full
• Delete 1
• Print the list 769
• Delete 6
• Print the list 79
• Write a class studentInfo that represents a student
record. It must have variables to store the student ID,
student’s name and student’s CGPA. It also must have a
function to print all the values. You will also need to
overload a few operators.
• Create a list of objects of class studentInfo.
• Insert 5 student records 15234 Jon 2.6
13732 Tyrion 3.9
13569 Sandor 1.2
15467 Ramsey 2 3.1
16285 Arya 3.1
• Delete the record with ID 15467
• Retrieve the record with ID 13569 and print whether Item is found
found or not along with the entire record 13569, Sandor, 1.2
• Print the list 15234, Jon, 2..6
13732, Tyrion, 3.9
13569, Sandor, 1.2
16285, Arya, 3.1
CSE225L – Data Structures and Algorithms Lab
Lab 05
Sorted List (array based)

In today’s lab we will design and implement the List ADT where the items in the list are sorted.

sortedtype.h template <class ItemType>


void SortedType<ItemType>::InsertItem(ItemType
#ifndef SORTEDTYPE_H_INCLUDED item)
#define SORTEDTYPE_H_INCLUDED {
int location = 0;
const int MAX_ITEMS = 5; bool moreToSearch = (location < length);
template <class ItemType>
class SortedType while (moreToSearch)
{ {
public : if(item > info[location])
SortedType(); {
void MakeEmpty(); location++;
bool IsFull(); moreToSearch = (location < length);
int LengthIs(); }
void InsertItem(ItemType); else if(item < info[location])
void DeleteItem(ItemType); moreToSearch = false;
void RetrieveItem(ItemType&, }
bool&); for (int index = length; index > location;
void ResetList(); index--)
void GetNextItem(ItemType&); info[index] = info[index - 1];
private: info[location] = item;
int length; length++;
ItemType info[MAX_ITEMS]; }
int currentPos; template <class ItemType>
}; void SortedType<ItemType>::DeleteItem(ItemType
item)
#endif // SORTEDTYPE_H_INCLUDED
{
int location = 0;
sortedtype.cpp
while (item != info[location])
#include "sortedtype.h" location++;
template <class ItemType> for (int index = location + 1; index < length;
SortedType<ItemType>::SortedType() index++)
{ info[index - 1] = info[index];
length = 0; length--;
}
currentPos = - 1;
template <class ItemType>
}
void SortedType<ItemType>::RetrieveItem(ItemType&
template <class ItemType> item, bool& found)
void SortedType<ItemType>::MakeEmpty() {
{ int midPoint, first = 0, last = length - 1;
length = 0; bool moreToSearch = (first <= last);
} found = false;
template <class ItemType> while (moreToSearch && !found)
bool SortedType<ItemType>::IsFull() {
{ midPoint = (first + last) / 2;
return (length == MAX_ITEMS); if(item < info[midPoint])
} {
template <class ItemType> last = midPoint - 1;
moreToSearch = (first <= last);
int SortedType<ItemType>::LengthIs()
}
{ else if(item > info[midPoint])
return length; {
} first = midPoint + 1;
template <class ItemType> moreToSearch = (first <= last);
void SortedType<ItemType>::ResetList() }
{ else
currentPos = - 1; {
} found = true;
template <class ItemType> item = info[midPoint];
void }
SortedType<ItemType>::GetNextItem(ItemType& }
item) }
{
currentPos++;
item = info [currentPos];
}
Generate the driver file (main.cpp) where you perform the following tasks. Note that you cannot make any change to
the header file or the source file.

Operation to Be Tested and Description of Action Input Values Expected Output


• Create a list of integers
• Print length of the list 0

• Insert five items 5 7 4 2 1
•• Print the list 1 2 4 5 7
• Retrieve 6 and print whether found Item is not found
• Retrieve 5 and print whether found Item is found
• Print if the list is full or not List is full
• Delete 1
• Print the list 2 4 57
• Print if the list is full or not List is not full
• Write a class timeStamp that represents a time of the
day. It must have variables to store the number of
seconds, minutes and hours passed. It also must have a
function to print all the values. You will also need to
overload a few operators.
• Create a list of objects of class timeStamp.
• Insert 5 time values in the format ssmmhh 15 34 23
13 13 02
43 45 12
25 36 17
52 02 20
• Delete the timestamp 25 36 17
• Print the list 15:34:23
13:13:02
43:45:12
52:02:20
CSE225L – Data Structures and Algorithms Lab
Lab 04
Stack (array based)

In today’s lab we will design and implement the Stack ADT using array.

stacktype.h stacktype.cpp

#ifndef STACKTYPE_H_INCLUDED #include "StackType.h"


#define STACKTYPE_H_INCLUDED template <class ItemType>
StackType<ItemType>::StackType()
const int MAX_ITEMS = 5; {
top = -1;
class FullStack }
// Exception class thrown template <class ItemType>
// by Push when stack is full. bool StackType<ItemType>::IsEmpty()
{}; {
class EmptyStack return (top == -1);
// Exception class thrown }
// by Pop and Top when stack is emtpy. template <class ItemType>
{}; bool StackType<ItemType>::IsFull()
{
template <class ItemType> return (top == MAX_ITEMS-1);
class StackType }
{ template <class ItemType>
public: void StackType<ItemType>::Push(ItemType newItem)
StackType(); {
bool IsFull(); if( IsFull() ) throw FullStack();
bool IsEmpty(); top++;
void Push(ItemType); items[top] = newItem;
void Pop(); }
ItemType Top(); template <class ItemType>
private: void StackType<ItemType>::Pop()
int top; {
ItemType items[MAX_ITEMS]; if( IsEmpty() ) throw EmptyStack();
}; top--;
}
#endif // STACKTYPE_H_INCLUDED template <class ItemType>
ItemType StackType<ItemType>::Top()
{
if (IsEmpty()) throw EmptyStack();
return items[top];
}
Generate the driver file (main.cpp) where you perform the following tasks. Note that you cannot make any change to
the header file or the source file.

Operation to Be Tested and Description of Action Input Values Expected Output


• Create a stack of integers
• Check if the stack is empty Stack is Empty

• Push four items 5 7 4 2
• Check if the stack is empty Stack is not Empty
• Check if the stack is full Stack is not full
• Print the values in the stack (in the order the values are given as 5 7 4 2
input)
• Push another item 3
• Print the values in the stack 5 7 4 2 3
• Check if the stack is full Stack is full
• Pop two items
• Print top item 4
• Take strings of parentheses from the user as input and use a stack to () Balanced
check if the string of parentheses is balanced or not (())()(()())() Balanced
(())()((() Not balanced
(())))((() Not balanced
CSE225L – Data Structures and Algorithms Lab
Lab 07
Queue (array based)

In today’s lab we will design and implement the Queue ADT using array.

quetype.h template<class ItemType>


QueType<ItemType>::~QueType()
#ifndef QUETYPE_H_INCLUDED {
#define QUETYPE_H_INCLUDED delete [] items;
}
class FullQueue template<class ItemType>
{}; void QueType<ItemType>::MakeEmpty()
class EmptyQueue {
{}; front = maxQue - 1;
template<class ItemType> rear = maxQue - 1;
class QueType }
{ template<class ItemType>
public: bool QueType<ItemType>::IsEmpty()
QueType(); {
QueType(int max); return (rear == front);
~QueType(); }
void MakeEmpty(); template<class ItemType>
bool IsEmpty(); bool QueType<ItemType>::IsFull()
bool IsFull(); {
void Enqueue(ItemType); return ((rear+1)%maxQue == front);
void Dequeue(ItemType&); }
private: template<class ItemType>
int front; void QueType<ItemType>::Enqueue(ItemType newItem)
int rear; {
ItemType* items; if (IsFull())
int maxQue; throw FullQueue();
}; else
{
#endif // QUETYPE_H_INCLUDED rear = (rear +1) % maxQue;
items[rear] = newItem;
quetype.cpp }
}
#include "quetype.h" template<class ItemType>
void QueType<ItemType>::Dequeue(ItemType& item)
template<class ItemType> {
QueType<ItemType>::QueType(int max) if (IsEmpty())
{ throw EmptyQueue();
maxQue = max + 1; else
front = maxQue - 1; {
rear = maxQue - 1; front = (front + 1) % maxQue;
items = new ItemType[maxQue]; item = items[front];
} }
template<class ItemType> }
QueType<ItemType>::QueType()
{
maxQue = 501;
front = maxQue - 1;
rear = maxQue - 1;
items = new ItemType[maxQue];
}
Generate the driver file (main.cpp) where you perform the following tasks. Note that you cannot make any change to
the header file or the source file.

Operation to Be Tested and Description of Action Input Values Expected Output


• Create a queue of integers of size 5
• Print if the queue is empty or not Queue is Empty
• Enqueue four items 5 7 4 2
• Print if the queue is empty or not Queue is not Empty
• Print if the queue is full or not Queue is not full
• Enqueue another item 6
• Print the values in the queue (in the order the values are given as 5 7 4 2 6
input)
• Print if the queue is full or not Queue is Full
• Enqueue another item 8 Queue Overflow
• Dequeue two items
• Print the values in the queue (in the order the values are given as 4 2 6
input)
• Dequeue three items
• Print if the queue is empty or not Queue is Empty
• Dequeue an item Queue Underflow
• Take an integer n from the user as input and use a queue to print 10 1
binary values of each integer from 1 to n. Here is how it can be 10
done. 11
o Create an empty queue 100
o Enqueue the first binary number “1” to the queue. 101
o Now run a loop for generating and printing n binary 110
numbers. 111
▪ Dequeue and print the value. 1000
▪ Append “0” at the dequeued value and enqueue it. 1001
▪ Append “1” at the dequeued value and enqueue it. 1010
CSE225L – Data Structures and Algorithms Lab
Lab 08
Stack (Linked List)

In today’s lab we will design and implement the Stack ADT using linked list.
stacktype.h template <class ItemType>
bool StackType<ItemType>::IsFull()
#ifndef STACKTYPE_H_INCLUDED {
#define STACKTYPE_H_INCLUDED NodeType* location;
class FullStack try
{}; {
class EmptyStack location = new NodeType;
{}; delete location;
template <class ItemType> return false;
class StackType }
{ catch(bad_alloc& exception)
struct NodeType {
{ return true;
ItemType info; }
NodeType* next; }
}; template <class ItemType>
public: void StackType<ItemType>::Push(ItemType newItem)
StackType(); {
~StackType(); if (IsFull())
void Push(ItemType); throw FullStack();
void Pop(); else
ItemType Top(); {
bool IsEmpty(); NodeType* location;
bool IsFull(); location = new NodeType;
private: location->info = newItem;
NodeType* topPtr; location->next = topPtr;
}; topPtr = location;
#endif // STACKTYPE_H_INCLUDED }
}
stacktype.cpp template <class ItemType>
void StackType<ItemType>::Pop()
#include <iostream> {
#include "stacktype.h" if (IsEmpty())
using namespace std; throw EmptyStack();
else
template <class ItemType> {
StackType<ItemType>::StackType() NodeType* tempPtr;
{ tempPtr = topPtr;
topPtr = NULL; topPtr = topPtr->next;
} delete tempPtr;
}
template <class ItemType> }
bool StackType<ItemType>::IsEmpty() template <class ItemType>
{ StackType<ItemType>::~StackType()
return (topPtr == NULL); {
} NodeType* tempPtr;
while (topPtr != NULL)
template <class ItemType> {
ItemType StackType<ItemType>::Top() tempPtr = topPtr;
{ topPtr = topPtr->next;
if (IsEmpty()) delete tempPtr;
throw EmptyStack(); }
else }
return topPtr->info;
}
Generate the driver file (main.cpp) where you perform the following tasks. Note that you cannot make any change to
the header file or the source file.
Operation to Be Tested and Description of Action Input Values Expected Output
• Take infix expressions from the user as input, 10 + 3 * 5 / (16 - 4) 11.25
determine the outcome of the expression and gives (5 + 3) * 12 / 3 32
that back to user as output, or the text “Invalid 3 + 4 / (2 - 3) * / 5 Invalid expression
expression” if the expression is not a valid one. You 7 / 5 + (4 - (2) * 3 Invalid expression
will have to solve this problem in two steps. First, you
have to convert the expression from infix notation to
postfix notation. You are going to need a stack in
order to do so. In the next step, you will have to
evaluate the postfix expression and determine the
final result. Again, you will need a stack in order to
do this. All the operands in the infix expressions are
single digit non-negative operands and the operators
include addition (+), subtraction (-), multiplication (*)
and division (/).
CSE225L – Data Structures and Algorithms Lab
Lab 09
Queue (Linked List)

In today’s lab we will design and implement the Queue ADT using linked list.
quetype.h template <class ItemType>
void QueType<ItemType>::Enqueue(ItemType newItem)
#ifndef QUETYPE_H_INCLUDED {
#define QUETYPE_H_INCLUDED if (IsFull())
class FullQueue throw FullQueue();
{}; else
class EmptyQueue {
{}; NodeType* newNode;
template <class ItemType> newNode = new NodeType;
class QueType newNode->info = newItem;
{ newNode->next = NULL;
struct NodeType if (rear == NULL)
{ front = newNode;
ItemType info; else
NodeType* next; rear->next = newNode;
}; rear = newNode;
public: }
QueType(); }
~QueType(); template <class ItemType>
void MakeEmpty(); void QueType<ItemType>::Dequeue(ItemType& item)
void Enqueue(ItemType); {
void Dequeue(ItemType&); if (IsEmpty())
bool IsEmpty(); throw EmptyQueue();
bool IsFull(); else
private: {
NodeType *front, *rear; NodeType* tempPtr;
}; tempPtr = front;
item = front->info;
#endif // QUETYPE_H_INCLUDED front = front->next;
quetype.cpp if (front == NULL)
rear = NULL;
#include "quetype.h" delete tempPtr;
#include <iostream> }
using namespace std; }
template <class ItemType>
template <class ItemType> void QueType<ItemType>::MakeEmpty()
QueType<ItemType>::QueType() {
{ NodeType* tempPtr;
front = NULL; while (front != NULL)
rear = NULL; {
} tempPtr = front;
template <class ItemType> front = front->next;
bool QueType<ItemType>::IsEmpty() delete tempPtr;
{ }
return (front == NULL); rear = NULL;
} }
template<class ItemType> template <class ItemType>
bool QueType<ItemType>::IsFull() QueType<ItemType>::~QueType()
{ {
NodeType* location; MakeEmpty();
try }
{
location = new NodeType;
delete location;
return false;
}
catch(bad_alloc& exception)
{
return true;
}
}
Generate the Driver file (main.cpp) and check your program with the following outputs:
Operation to Be Tested and Description of Action Input Values Expected Output
• Given a set of coin values and an amount of money, 3 2 3 5 11 3
determine the minimum number of coins to make the given 3 5 20 30 40 2
amount of money. The input starts with an integer n,
specifying the number of coin types. Next n integers are the
coin values. The final integer is the amount of money you
have to make. You can assume that the amount will always
be possible to make using the given coin types.
• Try the input 3 2 3 5 200. Explain your program’s outcome
with this input.
CSE225L – Data Structures and Algorithms Lab
Lab 10
Unsorted List (linked list based)

In today’s lab we will design and implement the List ADT where the items in the list are unsorted.

unsortedtype.h template <class ItemType>


void UnsortedType<ItemType>::InsertItem(ItemType
#ifndef UNSORTEDTYPE_H_INCLUDED item)
#define UNSORTEDTYPE_H_INCLUDED {
NodeType* location;
template <class ItemType> location = new NodeType;
class UnsortedType location->info = item;
{ location->next = listData;
struct NodeType listData = location;
{ length++;
ItemType info; }
NodeType* next; template <class ItemType>
}; void UnsortedType<ItemType>::DeleteItem(ItemType
public: item)
UnsortedType(); {
~UnsortedType(); NodeType* location = listData;
bool IsFull(); NodeType* tempLocation;
int LengthIs(); if (item == listData->info)
void MakeEmpty(); {
void RetrieveItem(ItemType&, tempLocation = location;
bool&); listData = listData->next;
void InsertItem(ItemType); }
void DeleteItem(ItemType); else
void ResetList(); {
void GetNextItem(ItemType&); while (!(item==(location->next)->info))
private: location = location->next;
NodeType* listData; tempLocation = location->next;
int length; location->next = (location->next)->next;
NodeType* currentPos; }
}; delete tempLocation;
length--;
#endif // UNSORTEDTYPE_H_INCLUDED }
template <class ItemType>
unsortedtype.cpp void UnsortedType<ItemType>::RetrieveItem(ItemType&
item, bool& found)
#include "unsortedtype.h" {
#include <iostream> NodeType* location = listData;
using namespace std; bool moreToSearch = (location != NULL);
found = false;
template <class ItemType> while (moreToSearch && !found)
UnsortedType<ItemType>::UnsortedType() {
{ if (item == location->info)
length = 0; found = true;
listData = NULL; else
currentPos = NULL; {
} location = location->next;
template <class ItemType> moreToSearch = (location != NULL);
int UnsortedType<ItemType>::LengthIs() }
{ }
return length; }
} template <class ItemType>
template<class ItemType> void UnsortedType<ItemType>::MakeEmpty()
bool UnsortedType<ItemType>::IsFull() {
{ NodeType* tempPtr;
NodeType* location; while (listData != NULL)
try {
{ tempPtr = listData;
location = new NodeType; listData = listData->next;
delete location; delete tempPtr;
return false; }
} length = 0;
catch(bad_alloc& exception) }
{ template <class ItemType>
return true; UnsortedType<ItemType>::~UnsortedType()
} {
} MakeEmpty();
}
template <class ItemType>
void UnsortedType<ItemType>::ResetList()
{
currentPos = NULL;
}
template <class ItemType>
void UnsortedType<ItemType>::GetNextItem(ItemType&
item)
{
if (currentPos == NULL)
currentPos = listData;
else
currentPos = currentPos->next;
item = currentPos->info;
}

Generate the driver file (main.cpp) where you perform the following tasks. Note that you cannot make any change to
the header file or the source file.

Operation to Be Tested and Description of Action Input Values


• You are given two sequences of integers arranged in 10 1 5 6 10 14 20 25 31 38 40
ascending order. Your task is to combine the sequences into 12 2 4 7 9 16 19 23 24 32 35 36 42
one ascending sequence. In order to get full marks, you have
to make sure that the time complexity of combining two
sequences is O(N). You can safely assume that no integer will
be repeated. Input starts with a positive integer m which Expected Output
specifies the number of elements in the first sequence. Next m 1 2 4 5 6 7 9 10 14 16 19 20 23 24
values are the elements in the first sequence. The next positive 25 31 32 35 36 38 40 42
integer n specifies the number of elements in the second
sequence. Next n values are the elements in the second
sequence. The output is the combined sequence.
CSE225L – Data Structures and Algorithms Lab
Lab 11
Sorted List (linked list based)

In today’s lab we will design and implement the List ADT where the items in the list are sorted.

sortedtype.h template <class ItemType>


void SortedType<ItemType>::InsertItem(ItemType item)
#ifndef SORTEDTYPE_H_INCLUDED {
#define SORTEDTYPE_H_INCLUDED NodeType* newNode;
NodeType* predLoc;
template <class ItemType> NodeType* location;
class SortedType bool moreToSearch;
{
struct NodeType location = listData;
{ predLoc = NULL;
ItemType info; moreToSearch = (location != NULL);
NodeType* next; while (moreToSearch)
}; {
public: if (location->info < item)
SortedType(); {
~SortedType(); predLoc = location;
bool IsFull(); location = location->next;
int LengthIs(); moreToSearch = (location != NULL);
void MakeEmpty(); }
void RetrieveItem(ItemType&, else moreToSearch = false;
bool&); }
void InsertItem(ItemType); newNode = new NodeType;
void DeleteItem(ItemType); newNode->info = item;
void ResetList();
void GetNextItem(ItemType&); if (predLoc == NULL)
private: {
NodeType* listData; newNode->next = listData;
int length; listData = newNode;
NodeType* currentPos; }
}; else
{
#endif // SORTEDTYPE_H_INCLUDED newNode->next = location;
predLoc->next = newNode;
sortedtype.cpp
}
length++;
#include "sortedtype.h" }
#include <iostream> template <class ItemType>
using namespace std; void SortedType<ItemType>::DeleteItem(ItemType item)
{
template <class ItemType> NodeType* location = listData;
SortedType<ItemType>::SortedType() NodeType* tempLocation;
{ if (item == listData->info)
length = 0; {
listData = NULL; tempLocation = location;
currentPos = NULL; listData = listData->next;
} }
else
template <class ItemType>
{
int SortedType<ItemType>::LengthIs() while (!(item==(location->next)->info))
{ location = location->next;
return length; tempLocation = location->next;
} location->next = (location->next)->next;
template<class ItemType> }
bool SortedType<ItemType>::IsFull() delete tempLocation;
{ length--;
NodeType* location; }
try
{
location = new NodeType;
delete location;
return false;
}
catch(bad_alloc& exception)
{
return true;
}
}
template <class ItemType> template <class ItemType>
void SortedType<ItemType>::~SortedType()
SortedType<ItemType>::RetrieveItem(ItemType {
& item, bool& found) MakeEmpty();
{ }
NodeType* location = listData; template <class ItemType>
bool moreToSearch = (location != NULL); void SortedType<ItemType>::ResetList()
found = false; {
while (moreToSearch && !found) currentPos = NULL;
{ }
if (item == location->info)
found = true; template <class ItemType>
else if (item > location->info) void
{ SortedType<ItemType>::GetNextItem(ItemType
location = location->next; & item)
moreToSearch = (location != {
NULL); if (currentPos == NULL)
} currentPos = listData;
else else
moreToSearch = false; currentPos = currentPos->next;
} item = currentPos->info;
} }
template <class ItemType>
void SortedType<ItemType>::MakeEmpty()
{
NodeType* tempPtr;
while (listData != NULL)
{
tempPtr = listData;
listData = listData->next;
delete tempPtr;
}
length = 0;
}

Generate the driver file (main.cpp) where you perform the following tasks. Note that you cannot make any change to
the header file or the source file.

Operation to Be Tested and Description of Action Input Values Expected Output


• Write a class timeStamp that represents a time of the
day. It must have variables to store the number of
seconds, minutes and hours passed. It also must have a
function to print all the values. You will also need to
overload a few operators.
• Create a list of objects of class timeStamp.
• Insert 5 time values in the format ssmmhh 15 34 23
13 13 02
43 45 12
25 36 17
52 02 20
• Delete the timestamp 25 36 17
• Print the list 15:34:23
13:13:02
43:45:12
52:02:20
CSE225L – Data Structures and Algorithms Lab
Lab 12
Recursion

1. Write a recursive function that returns the nth Fibonacci number from the Fibonacci
series.
int fib(int n);

2. Write a recursive function to find the factorial of a number.


int factorial(int n);

3. Write a recursive function that returns the sum of the digits of an integer.

int sumOfDigits(int x);

4. Write a recursive function that find the minimum element in an array of integers.
int findMin(int a[], int size);

5. Write a recursive function that converts a decimal number to binary number.


int DecToBin(int dec);

6. Write a recursive function that find the sum of the following series.
1 + 1/2 + 1/4 + 1/8 + ... + 1/2n
CSE225L – Data Structures and Algorithms Lab
Lab 13
Binary Search Tree
In today’s lab we will design and implement the Binary Search Tree ADT.

binarysearchtree.h template <class ItemType>


#ifndef BINARYSEARCHTREE_H_INCLUDED bool TreeType<ItemType>::IsEmpty()
#define BINARYSEARCHTREE_H_INCLUDED {
#include "quetype.h" return root == NULL;
template <class ItemType> }
struct TreeNode template <class ItemType>
{ bool TreeType<ItemType>::IsFull()
ItemType info; {
TreeNode* left; TreeNode<ItemType>* location;
TreeNode* right; try
}; {
enum OrderType {PRE_ORDER, IN_ORDER, location = new TreeNode<ItemType>;
POST_ORDER}; delete location;
template <class ItemType> return false;
class TreeType }
{ catch(bad_alloc& exception)
public: {
TreeType(); return true;
~TreeType(); }
void MakeEmpty(); }
bool IsEmpty(); template <class ItemType>
bool IsFull(); int CountNodes(TreeNode<ItemType>* tree)
int LengthIs(); {
void RetrieveItem(ItemType& item, if (tree == NULL)
bool& found); return 0;
void InsertItem(ItemType item); else
void DeleteItem(ItemType item); return CountNodes(tree->left) +
void ResetTree(OrderType order); CountNodes(tree->right) + 1;
void GetNextItem(ItemType& item, }
OrderType order, bool& finished); template <class ItemType>
void Print(); int TreeType<ItemType>::LengthIs()
private: {
TreeNode<ItemType>* root; return CountNodes(root);
QueType<ItemType> preQue; }
QueType<ItemType> inQue; template <class ItemType>
QueType<ItemType> postQue; void Retrieve(TreeNode<ItemType>* tree, ItemType&
}; item, bool& found)
#endif // BINARYSEARCHTREE_H_INCLUDED {
binarysearchtree.cpp if (tree == NULL)
#include "binarysearchtree.h" found = false;
#include "quetype.cpp" else if (item < tree->info)
#include <iostream> Retrieve(tree->left, item, found);
using namespace std; else if (item > tree->info)
template <class ItemType> Retrieve(tree->right, item, found);
TreeType<ItemType>::TreeType() else
{ {
root = NULL; item = tree->info;
} found = true;
template <class ItemType> }
void Destroy(TreeNode<ItemType>*& tree) }
{ template <class ItemType>
if (tree != NULL) void TreeType<ItemType>::RetrieveItem(ItemType&
{ item, bool& found)
Destroy(tree->left); {
Destroy(tree->right); Retrieve(root, item, found);
delete tree; }
tree = NULL;
}
}
template <class ItemType>
TreeType<ItemType>::~TreeType()
{
Destroy(root);
}
template <class ItemType>
void TreeType<ItemType>::MakeEmpty()
{
Destroy(root);
}
template <class ItemType> template <class ItemType>
void Insert(TreeNode<ItemType>*& tree, void PreOrder(TreeNode<ItemType>* tree,
ItemType item) QueType<ItemType>& Que)
{ {
if (tree == NULL) if (tree != NULL)
{ {
tree = new TreeNode<ItemType>; Que.Enqueue(tree->info);
tree->right = NULL; PreOrder(tree->left, Que);
tree->left = NULL; PreOrder(tree->right, Que);
tree->info = item; }
} }
else if (item < tree->info) template <class ItemType>
Insert(tree->left, item); void InOrder(TreeNode<ItemType>* tree,
else QueType<ItemType>& Que)
Insert(tree->right, item); {
} if (tree != NULL)
template <class ItemType> {
void TreeType<ItemType>::InsertItem(ItemType InOrder(tree->left, Que);
item) Que.Enqueue(tree->info);
{ InOrder(tree->right, Que);
Insert(root, item); }
} }
template <class ItemType> template <class ItemType>
void Delete(TreeNode<ItemType>*& tree, void PostOrder(TreeNode<ItemType>* tree,
ItemType item) QueType<ItemType>& Que)
{ {
if (item < tree->info) if (tree != NULL)
Delete(tree->left, item); {
else if (item > tree->info) PostOrder(tree->left, Que);
Delete(tree->right, item); PostOrder(tree->right, Que);
else Que.Enqueue(tree->info);
DeleteNode(tree); }
} }
template <class ItemType> template <class ItemType>
void DeleteNode(TreeNode<ItemType>*& tree) void TreeType<ItemType>::ResetTree(OrderType
{ order)
ItemType data; {
TreeNode<ItemType>* tempPtr; switch (order)
{
tempPtr = tree; case PRE_ORDER:
if (tree->left == NULL) PreOrder(root, preQue);
{ break;
tree = tree->right; case IN_ORDER:
delete tempPtr; InOrder(root, inQue);
} break;
else if (tree->right == NULL) case POST_ORDER:
{ PostOrder(root, postQue);
tree = tree->left; break;
delete tempPtr; }
} }
else template <class ItemType>
{ void TreeType<ItemType>::GetNextItem(ItemType&
GetPredecessor(tree->left, data); item, OrderType order, bool& finished)
tree->info = data; {
Delete(tree->left, data); finished = false;
} switch (order)
} {
template <class ItemType> case PRE_ORDER:
void GetPredecessor(TreeNode<ItemType>* preQue.Dequeue(item);
tree, ItemType& data) if(preQue.IsEmpty())
{ finished = true;
while (tree->right != NULL) break;
tree = tree->right; case IN_ORDER:
data = tree->info; inQue.Dequeue(item);
} if(inQue.IsEmpty())
template <class ItemType> finished = true;
void TreeType<ItemType>::DeleteItem(ItemType break;
item) case POST_ORDER:
{ postQue.Dequeue(item);
Delete(root, item); if(postQue.IsEmpty())
} finished = true;
break;
}
}
template <class ItemType>
void PrintTree(TreeNode<ItemType>* tree)
{
if (tree != NULL)
{
PrintTree(tree->left);
cout << tree->info << " ";
PrintTree(tree->right);
}
}
template <class ItemType>
void TreeType<ItemType>::Print()
{
PrintTree(root);
}

Now generate the Driver file (main.cpp) where you perform the following tasks:

Operation to Be Tested and Description of Action Input Values Expected Output


• Create a tree object
• Print if the tree is empty or not Tree is empty

• Insert ten items 4 9 2 7 3 11 17 0 5 1
• Print if the tree is empty or not Tree is not empty
• Print the length of the tree 10
• Retrieve 9 and print whether found or not Item is found
• Retrieve 13 and print whether found or not Item is not found
• Print the elements in the tree (inorder) 0 1 2 3 4 5 7 9 11 17
• Print the elements in the tree (preorder) 4 2 0 1 3 9 7 5 11 17
• Print the elements in the tree (postorder) 1 0 3 2 5 7 17 11 9 4
• Make the tree empty
• Given a sequence of integers, determine the best ordering of 11 9 4 2 7 3 17 0 5 1 4 1 0 2 3 9 5 7 11 17
the integers to insert them into a binary search tree. The best
order is the one that will allow the binary search tree to have
the minimum height.

Hint: Sort the sequence (use the inorder traversal). The middle
element is the root. Insert it into an empty tree. Now in the
same way, recursively build the left subtree and then the right
subtree.
CSE225L – Data Structures and Algorithms Lab
Lab 14
Priority Queue
In today’s lab we will design and implement the Priority Queue ADT.

heaptype.h pqtype.h
#ifndef HEAPTYPE_H_INCLUDED #ifndef PQTYPE_H_INCLUDED
#define HEAPTYPE_H_INCLUDED #define PQTYPE_H_INCLUDED
template<class ItemType> #include "heaptype.h"
struct HeapType #include "heaptype.cpp"
{ class FullPQ
void ReheapDown(int root, int bottom); {};
void ReheapUp(int root, int bottom); class EmptyPQ
ItemType* elements; {};
int numElements; template<class ItemType>
}; class PQType
#endif // HEAPTYPE_H_INCLUDED {
heaptype.cpp public:
#include "heaptype.h" PQType(int);
template<class ItemType> ~PQType();
void Swap(ItemType& one, ItemType& two) void MakeEmpty();
{ bool IsEmpty();
ItemType temp; bool IsFull();
temp = one; void Enqueue(ItemType);
one = two; void Dequeue(ItemType&);
two = temp; private:
} int length;
template<class ItemType> HeapType<ItemType> items;
void HeapType<ItemType>::ReheapDown(int root, int bottom) int maxItems;
{ };
int maxChild; #endif // PQTYPE_H_INCLUDED
int rightChild; pqtype.cpp
int leftChild; #include "pqtype.h"
template<class ItemType>
leftChild = root*2+1; PQType<ItemType>::PQType(int max)
rightChild = root*2+2; {
if (leftChild <= bottom) maxItems = max;
{ items.elements=new ItemType[max];
if (leftChild == bottom) length = 0;
maxChild = leftChild; }
else template<class ItemType>
{ PQType<ItemType>::~PQType()
if(elements[leftChild]<=elements[rightChild]) {
maxChild = rightChild; delete [] items.elements;
else }
maxChild = leftChild; template<class ItemType>
} void PQType<ItemType>::MakeEmpty()
if (elements[root] < elements[maxChild]) {
{ length = 0;
Swap(elements[root], elements[maxChild]); }
ReheapDown(maxChild, bottom); template<class ItemType>
} bool PQType<ItemType>::IsEmpty()
} {
} return length == 0;
template<class ItemType> }
void HeapType<ItemType>::ReheapUp(int root, int bottom) template<class ItemType>
{ bool PQType<ItemType>::IsFull()
int parent; {
if (bottom > root) return length == maxItems;
{ }
parent = (bottom-1) / 2;
if (elements[parent] < elements[bottom])
{
Swap(elements[parent], elements[bottom]);
ReheapUp(root, parent);
}
}
}
template<class ItemType> template<class ItemType>
void PQType<ItemType>::Enqueue(ItemType newItem) void PQType<ItemType>::Dequeue(ItemType& item)
{ {
if (length == maxItems) if (length == 0)
throw FullPQ(); throw EmptyPQ();
else else
{ {
length++; item = items.elements[0];
items.elements[length-1] = newItem; items.elements[0] =
items.ReheapUp(0, length-1); items.elements[length-1];
} length--;
} items.ReheapDown(0, length-1);
}
}

Now generate the Driver file (main.cpp) where you perform the following tasks:

Operation to Be Tested and Description of Action Input Values Expected Output


• Create a PQType object with size 15
• Print if the queue is empty or not Queue is empty

• Insert ten items, in the order they appear 4 9 2 7 3 11 17 0 5 1
• Print if the queue is empty or not Queue is not empty
• Dequeue one element and print the dequeued value 17
• Dequeue one element and print the dequeued value 11
• You have N magical bags of candies in front of you. The 5 3 2 1 7 4 2 14
ith bag has Ai candies in it. It takes you one minute to
finish a bag of candies, no matter how many candies in
it. Every time you finish a bag with X candies in it, the
bag is magically replenished with X/2 (rounded down to
the nearest integer) more candies. Write a program
that determines the maximum number of candies you
can eat in K minutes.

The input is a sequence of integers. The first integer N


is the number of bags. The next integer K is the number
of minutes you have. The next N integers is the number
of candies in the bags. The output of your program is a
single integer which represents the maximum number
of candies you can eat.
CSE225L – Data Structures a nd Alg o rithms Lab
Lab 15
Graph
In today’s lab we will design and implement the Graph ADT.

graphtype.h template<class VertexType>


#ifndef GRAPHTYPE_H_INCLUDED GraphType<VertexType>::~GraphType()
#define GRAPHTYPE_H_INCLUDED {
#include "stacktype.h" delete [] vertices;
#include "quetype.h" delete [] marks;
template<class VertexType> for(int i=0;i<maxVertices;i++)
class GraphType delete [] edges[i];
{ delete [] edges;
public: }
GraphType(); template<class VertexType>
GraphType(int maxV); void GraphType<VertexType>::MakeEmpty()
~GraphType(); {
void MakeEmpty(); numVertices = 0;
bool IsEmpty(); }
bool IsFull(); template<class VertexType>
void AddVertex(VertexType); bool GraphType<VertexType>::IsEmpty()
void AddEdge(VertexType, {
VertexType, int); return (numVertices == 0);
int WeightIs(VertexType, }
VertexType); template<class VertexType>
void GetToVertices(VertexType, bool GraphType<VertexType>::IsFull()
QueType<VertexType>&); {
void ClearMarks(); return (numVertices == maxVertices);
void MarkVertex(VertexType); }
bool IsMarked(VertexType); template<class VertexType>
void DepthFirstSearch(VertexType, void GraphType<VertexType>::AddVertex(VertexType
VertexType); vertex)
void BreadthFirstSearch(VertexType, {
VertexType); vertices[numVertices] = vertex;
private: for (int index=0; index<numVertices; index++)
int numVertices; {
int maxVertices; edges[numVertices][index] = NULL_EDGE;
VertexType* vertices; edges[index][numVertices] = NULL_EDGE;
int **edges; }
bool* marks; numVertices++;
}; }
#endif // GRAPHTYPE_H_INCLUDED template<class VertexType>
heaptype.cpp int IndexIs(VertexType* vertices, VertexType
#include "graphtype.h" vertex)
#include "stacktype.cpp" {
#include "quetype.cpp" int index = 0;
#include <iostream> while (!(vertex == vertices[index]))
using namespace std; index++;
const int NULL_EDGE = 0; return index;
}
template<class VertexType> template<class VertexType>
GraphType<VertexType>::GraphType() void GraphType<VertexType>::ClearMarks()
{ {
numVertices = 0; for(int i=0; i<maxVertices; i++)
maxVertices = 50; marks[i] = false;
vertices = new VertexType[50]; }
edges = new int*[50]; template<class VertexType>
for(int i=0;i<50;i++) void GraphType<VertexType>::MarkVertex(VertexType
edges[i] = new int [50]; vertex)
marks = new bool[50]; {
} int index = IndexIs(vertices, vertex);
template<class VertexType> marks[index] = true;
GraphType<VertexType>::GraphType(int maxV) }
{ template<class VertexType>
numVertices = 0; bool GraphType<VertexType>::IsMarked(VertexType
maxVertices = maxV; vertex)
vertices = new VertexType[maxV]; {
edges = new int*[maxV]; int index = IndexIs(vertices, vertex);
for(int i=0;i<maxV;i++) return marks[index];
edges[i] = new int [maxV]; }
marks = new bool[maxV];
}
template<class VertexType>
void GraphType<VertexType>::AddEdge(VertexType fromVertex, VertexType toVertex, int weight)
{
int row = IndexIs(vertices, fromVertex);
int col= IndexIs(vertices, toVertex);
edges[row][col] = weight;
}
template<class VertexType>
int GraphType<VertexType>::WeightIs(VertexType fromVertex, VertexType toVertex)
{
int row = IndexIs(vertices, fromVertex);
int col= IndexIs(vertices, toVertex);
return edges[row][col];
}
template<class VertexType>
void GraphType<VertexType>::GetToVertices(VertexType vertex, QueType<VertexType>& adjVertices)
{
int fromIndex, toIndex;
fromIndex = IndexIs(vertices, vertex);
for (toIndex = 0; toIndex < numVertices; toIndex++)
if (edges[fromIndex][toIndex] != NULL_EDGE)
adjVertices.Enqueue(vertices[toIndex]);
}
template<class VertexType> template<class VertexType>
void void
GraphType<VertexType>::DepthFirstSearch(Vertex GraphType<VertexType>::BreadthFirstSearch(Vertex
Type startVertex, VertexType endVertex) Type startVertex, VertexType endVertex)
{ {
StackType<VertexType> stack; QueType<VertexType> queue;
QueType<VertexType> vertexQ; QueType<VertexType> vertexQ;
bool found = false;
VertexType vertex, item; bool found = false;
VertexType vertex, item;
ClearMarks();
stack.Push(startVertex); ClearMarks();
do queue.Enqueue(startVertex);
{ do
vertex = stack.Top(); {
stack.Pop(); queue.Dequeue(vertex);
if (vertex == endVertex) if (vertex == endVertex)
{ {
cout << vertex << " "; cout << vertex << " ";
found = true; found = true;
} }
else else
{ {
if (!IsMarked(vertex)) if (!IsMarked(vertex))
{ {
MarkVertex(vertex); MarkVertex(vertex);
cout << vertex << " "; cout << vertex << " ";
GetToVertices(vertex,vertexQ); GetToVertices(vertex, vertexQ);
while (!vertexQ.IsEmpty())
{ while (!vertexQ.IsEmpty())
vertexQ.Dequeue(item); {
if (!IsMarked(item)) vertexQ.Dequeue(item);
stack.Push(item); if (!IsMarked(item))
} queue.Enqueue(item);
} }
} }
} while (!stack.IsEmpty() && !found); }
cout << endl; } while (!queue.IsEmpty() && !found);
if (!found) cout << endl;
cout << "Path not found." << endl; if (!found)
} cout << "Path not found." << endl;
}
Now generate the Driver file (main.cpp) where you perform the following tasks:

Operation to Be Tested and Description of Action Input Values Expected Output


• Generate the following graph. Assume that all edge costs are
1.
F

H G

E D

A
C

• Outdegree of a particular vertex in a graph is the number of


edges going out from that vertex to other vertices. For
instance the outdegree of vertex B in the above graph is 1.
Add a member function OutDegree to the GraphType
class which returns the outdegree of a given vertex.

int OutDegree(VertexType v);

• Add a member function to the class which determines if there


is an edge between two vertices.

bool FoundEdge(VertexType u, VertexType v);


• Print the outdegree of the vertex D. 3
• Print if there is an edge between vertices A and D. There is an edge.
• Print if there is an edge between vertices B and D. There is no edge.
• Use depth first search in order to find if there is a path from B BADGFHE
to E.

• Use depth first search in order to find if there is a path from E E


to B.
Path not found.
• Use breadth first search in order to find if there is a path from BACDE
B to E.
• Use breadth first search in order to find if there is a path from E
E to B.
Path not found.
• Modify the BreadthFirstSearch function so that it also
prints the length of the shortest path between two vertices.
• Determine the length of the shortest path from B to E. 3

You might also like