CS255 Data Structure Lab Manual
CS255 Data Structure Lab Manual
2012
Page 1
2012
Course Objectives:
1. Extend programming ability using an object oriented language.
2. Analyze algorithms to determine time and space complexity.
3. Build and manipulate linear and non-linear data structures, including stacks,
queues, linked lists, trees, and graphs.
4. Sort, search, and merge data.
5. Choose the appropriate data structure to use in solving typical computer
science problems.
Learning Outcomes:
After Completing this course the student must demonstrate the Knowledge and
ability to:
1. Demonstrate the application of software engineering principles in design, coding ,
and testing of large programs.
2. To introduce students to essential data structures such as linked lists, stacks,
queues, trees, and graphs. This introduction emphasizes the specification of each
structure as an abstract data type before discussing implementations and application
of the structure.
3. Make students aware of the importance of object oriented methods in
developing software.
4. Student must know the systematic approach to study algorithms , by focuses first
on understanding the action of the algorithm then analyzing it.
Evaluation Plan:
Students will be evaluated based on the following criteria:
Quizzes after finishing each lab subject
60%
Assignment, attendance, participation
10%
Final Lab Exam
30%
Course Plan
CS Department Faculty of IT Yarmouk University
Page 2
2012
Subjects and Contents
Week 1
Week 2
Week 3
Recursion
Design a recursive functions.
Week 4
Dynamic Array
Week 5
Creation
Passing to function
Insertion Implementation
Delete Implementation
Search Implementation
Sort Implementation
Separation implementation
Merge Implementation
Linked list
Week 6
Creation
Passing to function
Insertion Implementation
Delete Implementation
Search Implementation
Sort Implementation
Double linked list
Week 7
Stack
Creation
Passing to function
Insertion Implementation
Delete Implementation
Search Implementation
Sort Implementation
Separation implementation
Merge Implementation
ADT (array implementation)
Page 3
2012
queue ADT
(array implementation)
Week 11
Binary tree
Implement Binary tree traversal methods : Preorder, In-order, Postordered
traversal. Recursive Algorithms for above mentioned
Traversal methods.
Week 12
GOOD LUCK!!!
Page 4
2012
Array
AIM:To write a program that implements the basic operations of the
Array in C++.
Array
An array is a series of elements of the same type placed in contiguous memory
locations that can be individually referenced by adding an index to a unique identifier.
For example, we can store 5 values of type int in an array without having to declare 5
different variables, each one with a different identifier. Instead of that, using an array
we can store 5 different values of the same type, with a unique identifier.
Lab Question:
Write a program that computes the Summation of Array Values.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
int main ()
{
int billy [] = {16, 2, 77, 40, 12071};
int n, result=0;
for ( n=0 ; n<5 ; n++ )
{
result += billy[n];
}
cout << result;
return 0;
}
Output:12206
Excersise1:
Write A c++ Program That checks if a given Array is a Palindrome.
palindrome is a number that remains the same when its digits are reversed. Like
16461, for example
Excersise2:
Write A c++ Program Which Call A Function Which Sort The Given Array.
Page 5
2012
Dynamic Array
AIM:To write a program that implements a dynamic Array in C++.
Dynamic Array
Is a random access, variable-size list data structure that allows elements to be added
or removed. It is supplied with standard libraries in many modern mainstream
programming languages.
Lab Question:
Write A c++ Program Which Creates And Prints Dynamic Array Of Integer Type.
1. #include<iostream>
2. using namespace std;
3. class array {
4. private:
5. int size;
6. int *ptr;
7. public:
8. array(int s) {
9. size=s;
10. ptr=new int[size];
11. for(int a=0;a<size;a++)
12.
ptr[a]=0;
13. }
14. void read() {
15. for(int a=0;a<size;a++)
16.
cin>>ptr[a];
17. }
18. };
19.
20. void main() {
21. int x;
22. cout<<"Enter The Dynamic Array Size..."<<endl;
23. cin>>x;
24. array a1(x);
25. cout<<"Enter ur array elements.....\n";
26. a1.read();
27. cout<<"ur array elements Are........\n";
28. a1.print();
29. }
Excersises:
1. Write A c++ Program Which Delete By Shift The Median Value Of A Given
Dynamic Array.
2. Write A c++ Program Which Insert By Shift A New Value Before The
Maximum Value Of A Given Dynamic Array.
Page 6
2012
Lab Question:
Write a Recursive Function To Print Number From Given input down to 0
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
class rec1
{
public:
void printIt( int n ) {
if ( n == 0 ) cout << endl;// base case
else
{ printIt( n - 1 ); // recursive call
cout << n - 1 << ;
}
}
};
void main()
{
rec1 call;
call.printIt(5);
}
Output: 4 3 2 1 0
Excersise: use a recursive function to write a program that performs the following
tasks.
1. Find The Factorial Number For an input n.
2. Check If a Given Array Values Are Palindrome or not.
Page 7
2012
List is a collection of components, called nodes. Every node (except the last
node) contains the address of the next node. Every node in a linked list has
two components:
1. one to store the relevant information (that is, data)
2. one to store the address, called the link or next , of the next node in the
list.
The address of the first node in the list is stored in a separate location, called
the head or first
The address of the last node in the list is stored in a separate location, called
the tail or last
Lab Question:
Write class called node that contain:
CS Department Faculty of IT Yarmouk University
Page 8
2012
data members:
1. data as integer.
2. next as pointer of type node.
3. head as pointer of type node.
4. tail as pointer of type node.
5. current as pointer of type node.
6. count as integer.
The following functions:
1. constructor to initialize data member
2. Function called initializelist to enter values to list until reach to value -1.
3. Function called print to print list.
Then write main to test this class
Answer:
1. class node
2. {
3. private:
4. int data;
5. node *next;
6. node *current,*head,*tail;
7. public:
8. node(){
9.
head=current=tail=next=NULL;
10.
data=0;
11.
}
12.
void initializelist() { //create
13.
head=tail=current=new node;
14.
cin>>current->data;
15.
int x;
16.
cin>>x;
17.
while(x!=-1){
18.
current=new node;
19.
current->data=x;
20.
tail->next=current;
21.
tail=current;
22.
cin>>x;
}
23.
}
24.
void print() { //Print
25.
current=head;
26.
while(current!=tail) {
27.
cout<<current->data<<"\t";
28.
current=current->next;
29.
}
30.
cout<<tail->data<<"\t";
31.
cout<<endl;
32.
}
33.
};
34.
void main(){
35.
node LS;
36.
LS.initializelist();
37.
LS.print();
38.
}
Exercise 1:
Modify class node in Exercise 1 by adding the following:
CS Department Faculty of IT Yarmouk University
Page 9
2012
Exercise 2:
Modify class node in Exercise 1 by adding the following:
1. Function called InsertAtBegin to add node at the begging of list.
2. Function called InsertAtEnd to add node at the last of list.
3. Function called Insert to inset new value after specific value in list.
4. Function called DeleteFromBegin to delete node from the begging of list.
5. Function called DeleteFromEnd to delete node from the last of list.
6. Function called Delete to delete maximum value in list.
Page 10
2012
Lab Question:
Write class called node that contain:
data members:
7. data as integer.
8. next as pointer of type node.
9. back as pointer of type node.
10. head as pointer of type node.
11. tail as pointer of type node.
12. current as pointer of type node.
Page 11
2012
class node
{
private:
int data;
node *next , *back;
node *current,*head,*tail;
public:
node()
{
head=current=tail=next=NULL;
data=0;
}
void initializelist()//create
{
head=tail=current=new node;
cin>>current->data;
int x;
cin>>x;
while(x!=-1)
{
current=new node;
current->data=x;
head->next=current;
head=current;
cin>>x;
}
}
void print()//Print
{
current=head;
while(current!=tail)
{
cout<<current->data<<"\t";
current=current->next;
}
cout<<tail->data<<"\t";
cout<<endl;
}
};
Exercisevoid
1: main()
{
node
LS;
Modify class node
in Exercise
1 by adding the following:
LS.initializelist();
LS.print();
4. Function
called max to return maximum value in the list.
}
Page 12
2012
Stack ADT
AIM:To write a program for linked implementation of stack in C++
Stacks Overview
Stack is data structure in which the elements are added and removed from one
end only; a Last In First Out (LIFO) data structure
Lab Question:
Write class called Stack that contains:
data members:
1. size as integer.
2. stack as pointer of type stack.
3. stacktop as pointer of type stack.
The following functions:
1. constructor to initialize data member
2. intializestack to pushing elements to stack.
Then write main to test this class
Answer:
Page 13
2012
1. class Stack
2. {
3. private:
4. int maxsize;
5. int stacktop;
6. int *stack;
7. public:
8. array_stack(int s=100)
9. {
10.
maxsize=s;
11.
stack=new int[maxsize];
12.
stacktop=0;
13.
}
14.
};
Exercise 1:
Modify class node in Exercise 1 by adding the following:
1. Function Push to add element to stack
2. Function Pop to delete element from stack
3. Function isEmpty to true if stack is empty otherwise return false.
4. Function isFull to true if stack is empty otherwise return false.
5. Function top to retrieve elements at top of stack.
6. separate function called reverse to reverse elements of stack in another stack
Page 14
2012
Queue ADT
AIM:To write a program for array implementation of queue in C++
QUEUE:
The queue is a data structure that allows use of two ends of it. I mean from one
end of thequeue you can insert the elements and from another end of the queue
you can delete theelements.The Queue can be formally defined as ordered
collection of elements that has two endsnamed as front and rear. From the front
end one can delete the elements and from the rear endone can insert the
elements. The queue is also called as First in First out (FIFO) data structure.
TWO TYPES OF REPRESENTATIONS OF QUEUE
Array Representations
Linked list Representation
Basic operations:
Enqueue(x) : insert item x at the rear
Dequeue() : delete the rear element
Page 15
2012
ENQUEUE OPERATION
1) Get the element to be inserted
2) Check whether the queue is full.
3) If the queue is full
a. we cannot insert an element into the queue.
b. Queue is overflow error occurs.
4) ELSE
a. We may insert the element into the queue.
b. Rear= (rear + 1)%size;
c. queue[rear]= x;
DEQUEUE OPERATION
1) Check whether the queue is Empty.
2) If the queue is empty
a. we cannot delete an element from the queue.
b. Queue is empty error occurs.
3) ELSE
a. we maydelete an element from the queue.
b. x = queue[front];
c. Front = (front +1)%size;
d. Return x
Page 16
2012
Lab Question:
Write a C++ code to implement enqueue and dequeue using array.
1. # include<iostream.h>
2. # include<conio.h>
3. # define SIZE 20
4. class queue {
5. int a[SIZE];
6. int front;
7. int rear;
8. int count
9. queue();
10.
~queue();
11.
void insert(int i);
12.
void remove();
13.
bool isempty();
14.
bool isfull();
15.
};
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
queue::queue() {
front=0; rear=0; count =0;
}
void queue::insert(int i) {
if(isfull())
{
cout<<" ** Queue is FULL !!! No insertion
return;
}
a[rear] = i;
rear = (rear+1)%size;
}
void queue::remove() {
if(isempty())
cout<<"Queue Empty !!!";
else
front = (front+1)%size
}
bool queue::isempty()
{
return (count == 0) }
bool queue::isfull()
{
return (count == size) }
38.
39.
40.
41.
42.
43.
44.
45.
46.
void main() {
queue q;
q.insert(1);
q.insert(2);
q.remove();
q.remove();
q.remove();
getch();
}
**";
Page 17
2012
ENQUEUE OPERATION
1) Get the element to be inserted
2) Create a new node.
Node * p;
P = ( node * ) mallloc (size of ( node ) );
P -> data = x;
P -> next = NULL
3) If ( rear ! = NULL)
Rear -> next = p;
Rear = p;
4) Else
Front = p;
Rear = p;
DEQUEUE OPERATION
1) Check the condition whether the queue is empty or not.
2) If ( front = = NULL && rear = = NULL)
//we cannot delete element from the queue.
Cout << Queue underflow
3) ELSE
//We can delete element from it.
If (front == rear) //Check whether both the ends are equal.
Front = rear = NULL;
ELSE
Node * p;
P = front;
Front = front-> next
Delete (p)
Page 18
2012
Lab Question:Write a C++ code to implement enqueue and dequeue using array.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
#include<iostream>
#include<cstdlib>
using namespace std;
struct node{
int info;
struct node *next;
};
class Queue{
private:
node *rear;
node *front;
public:
Queue();
void enqueue();
void dequeue();
void display();
};
Queue::Queue(){
rear = NULL;
front = NULL;
}
void Queue::enqueue(){
int data;
node *temp = new node;
cout<<"Enter the data to enqueue: ";
cin>>data;
temp->info = data;
temp->next = NULL;
if(front == NULL){
front = temp;
}else{
rear->next = temp;
}
rear = temp;
}
void Queue::dequeue(){
node *temp = new node;
if(front == NULL){
cout<<"\nQueue is Emtpty\n";
}else{
temp = front;
front = front->next;
cout<<"The data Dequeued is "<<temp->info;
delete temp;
}
}
void Queue::display(){
node *p = new node;
p = front;
if(front == NULL){
Page 19
2012
cout<<"\nNothing to Display\n";
}else{
while(p!=NULL){
cout<<endl<<p->info;
p = p->next;
}
}
}
int main(){
Queue queue;
int choice;
while(true){
cout<<"\n1.Enqueue\n2. Dequeue\n3. Display\n 4.Quit";
cout<<"\nEnter your choice: ";
cin>>choice;
switch(choice){
case 1:
queue.enqueue();
break;
case 2:
queue.dequeue();
break;
case 3:
queue.display();
break;
case 4:
exit(0);
break;
default:
cout<<"\nInvalid Input. Try again! \n";
break;
}
}
return 0;
}
Page 20
2012
Binary Tree
Aim: Implement the Binary Tree Traversal
Procedure:
1) Make the structure of Binary Tree Traversal for integer numbers.
struct node {
int data;
struct node* left;
struct node* right;
}
2) implement inorder(), preorder() and postorder() traversal for it.
Preorder
1) Visit the root.
2) Traverse the left subtree.
3) Traverse the right subtree.
Inorder
1) Traverse the left subtree.
2) Visit the root.
3) Traverse the right subtree.
Postorder
1) Traverse the left subtree.
2) Traverse the right subtree.
3) Visit the root.
Lab Question:Write a C++ code to implement enqueue and dequeue using array.
1. #include <iostream>
2. #include <cstdlib>
3. using namespace std;
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
class BinaryTree
{
private:
struct tree_node
{
tree_node* left;
tree_node* right;
int data;
};
tree_node* root;
14.
15.
16.
17.
18.
public:
BinaryTree()
{
root = NULL;
}
Page 21
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
void BinaryTree::print_inorder()
{
inorder(root);
}
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
void BinaryTree::inorder(tree_node* p)
{
if(p != NULL)
{
if(p->left) inorder(p->left);
cout<<" "<<p->data<<" ";
if(p->right) inorder(p->right);
}
else return;
}
43.
44.
45.
46.
void BinaryTree::print_preorder()
{
preorder(root);
}
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
void BinaryTree::preorder(tree_node* p)
{
if(p != NULL)
{
cout<<" "<<p->data<<" ";
if(p->left) preorder(p->left);
if(p->right) preorder(p->right);
}
else return;
}
57.
58.
59.
60.
void BinaryTree::print_postorder()
{
postorder(root);
}
2012
Page 22
2012
{
if(p->left) postorder(p->left);
if(p->right) postorder(p->right);
cout<<" "<<p->data<<" ";
}
else return;
}
}
}
}
Page 23
2012
Insertion, Deletion
Insertion:
To insert a new node into the BST
Deletion:
Case 1: the node is a leaf
Delete it immediately
Case 2: the node has one child
Adjust a pointer from the parent to bypass that node
Case 3: the node has 2 children
Replace the key of that node with the minimum element at the right
subtree
Delete that minimum element
Has either no child or onlyone child because if it has a left
child, that left child would be smaller and would have been
chosen. So invoke case 1 or 2.
CS Department Faculty of IT Yarmouk University
Page 24
2012
Lab Question:Write a C++ code to implement binary search tree insertion and
deletion operations.
1. #include <iostream>
2. #include <cstdlib>
3. using namespace std;
4. class BinarySearchTree
5. {
6. private:
7. struct tree_node
8. {
9. tree_node* left;
10. tree_node* right;
11. int data;
12. };
13. tree_node* root;
14. public:
15. BinarySearchTree()
16. {
17. root = NULL;
18. }
19. bool isEmpty() const { return root==NULL; }
20. void insert(int);
21. void remove(int);
22. };
Page 25
2012
i. // 3 cases :
81. // 1. We're removing a leaf node
82. // 2. We're removing a node with a single child
83. // 3. we're removing a node with 2 children
CS Department Faculty of IT Yarmouk University
Page 26
2012
119.
{
if(parent->left == curr) parent->left = NULL;
else parent->right = NULL;
a. delete curr;
b. return;
}
120.
121.
122.
123.
124.
125.
Page 27
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.
if((curr->right)->left != NULL)
{
tree_node* lcurr;
tree_node* lcurrp;
lcurrp = curr->right;
lcurr = (curr->right)->left;
while(lcurr->left != NULL)
{
lcurrp = lcurr;
lcurr = lcurr->left;
}
curr->data = lcurr->data;
delete lcurr;
lcurrp->left = NULL;
}
else
{
tree_node* tmp;
tmp = curr->right;
curr->data = tmp->data;
curr->right = tmp->right;
delete tmp;
}
}
return;
}
}
2012
int main()
{
BinarySearchTree b;
int ch,tmp,tmp1;
while(1)
{
cout<<endl<<endl;
cout<<" Binary Search Tree Operations "<<endl;
cout<<" ----------------------------- "<<endl;
cout<<" 1. Insertion/Creation "<<endl;
cout<<" 2. Removal "<<endl;
Page 28
2012
Page 29