Вы находитесь на странице: 1из 119

MUFFAKHAM JAH COLLEGEL OF

ENGINEERING & TECHNOLOGY

Data Structures Lab Manual


B.E. II/IV I Sem
INFORMATION TECHNOLOGY

Be in a queue
Hello!!! its a stack

Linked list

Doubly linked
list

Prepared by
Ms. G. Vani & Ms. Husna Imroze

Mount Pleasant, 8-2-249, Road No. 3,


Banjara Hills, Hyderabad - 500 034,
Andhra Pradesh, India

Index
Introduction to Data Structures.
Various Data types and Data Structures.
A glimpse of few Important Data Structures.

3
3
8

Cycle-1

10

Cycle-2

54

Cycle-3

102

Introduction to Data Structures


What exactly is a Data Structure?
A data structure is a particular way of storing and organizing data in a computer so that
it can be used efficiently.
Data structures are generally based on the ability of a computer to fetch and store
data at any place in its memory, specified by an address a bit string that can be itself
stored in memory and manipulated by the program. Thus the record and array data
structures are based on computing the addresses of data items with arithmetic operations;
while the linked data structures are based on storing addresses of data items within the
structure itself. Many data structures use both principles, sometimes combined in nontrivial ways (as in XOR linking).

Various Data Structures or the Data Types:


Primitive types

Boolean
Character
Integer
String
Double
Float

Composite types

Struct
Union
Tagged union

Abstract data types

Container
Deque
List
Map
Multimap
Multiset
Priority queue
Queue
Set
Stack
String
Tree
3

Linear data structures


Arrays

Array
Dynamic array
Hashed array tree
Parallel array
Sparse array
Matrix
Sparse matrix
Circular buffer
Gap Buffer
Bit field
Bit array
Bitboard
Bitmaps
Images
Heightfields
Lookup table

Lists

Linked list
Doubly linked list
Xor linked list
Unrolled linked list
Zipper
VList
Skip list
Jump list
Self-organizing list

Trees
Binary trees

Binary tree
Binary search tree
Self-balancing binary search tree
Randomized binary search tree
Weight-balanced tree
Threaded binary tree
AVL tree
Red-black tree
AA tree
Scapegoat tree

Splay tree
T-tree
Rope
Top Trees
Tango Trees
Treap

B-trees

B-tree
B+ tree
B*-tree
B sharp tree
Dancing tree
2-3 tree
2-3-4 tree
Fusion tree
Bx-tree

Heaps

Heap
Binary heap
Binomial heap
Fibonacci heap
2-3 heap
Soft heap
Pairing heap
Leftist heap
Treap
Beap
Skew heap
Ternary heap
D-ary heap
Van Emde Boas tree

Tries
In these data structures each tree node compares a bit slice of key values.
Trie
Radix tree
Suffix tree
Suffix array
FM-index
Generalised suffix tree
B-trie
Judy array

Multiway trees

Ternary search tree


Andor tree
(a,b)-tree
Link/cut tree
SPQR-tree
Spaghetti stack
Disjoint-set data structure
Fusion tree
Enfilade
Exponential tree
Fenwick tree

Space-partitioning trees
This is data structures used for space partitioning or binary space partitioning.
Segment tree
Interval tree
Range tree
Bin
Kd-tree
Implicit kd-tree
Min/max kd-tree
Adaptive k-d tree
Kdb tree
Quadtree
Octree
Linear octrees
Z-order
UB-tree
R-tree
R+ tree
R* tree
Hilbert R-tree
X-tree
Metric tree
Cover tree
M tree
VP-tree
BK-tree
Bounding interval hierarchy
BSP tree

Application specific trees

Syntax tree
Abstract syntax tree
Parse tree
Decision tree
Alternating decision tree
Minimax tree
Expectiminimax tree
Finger tree

Hashes

Hash table
Bloom filter
Hash list
Hash tree
Prefix hash tree
Hash trie
Hash array mapped trie
Distributed hash table
Koorde

Graphs

Graph
Adjacency list
Adjacency matrix
Graph-structured stack
Scene graph
Binary decision diagram
Zero suppressed decision diagram
And-inverter graph
Propositional directed acyclic graph

A glimpse of few important Data Structures:


An array structure or simply array is a data structure
consisting of a collection of elements (values or variables),
each identified by one or more integer indices, stored so that
the address of each element can be computed from its index
tuple by a simple mathematical formula.
A stack is an abstract data type and data structure based on
the principle of Last In First Out (LIFO).A stack is an
ordered list of items.Items are removed from this list in the
reverse order to the order of their addition.
A queue is a particular kind of collection in which the
entities in the collection are kept in order and the principal
(or only) operations on the collection are the addition of
entities to the rear terminal position and removal of entities
from the front terminal position. This makes the queue a
First-In-First-Out (FIFO) data structure. In a FIFO data
structure, the first element added to the queue will be the
first one to be removed. This is equivalent to the
requirement that whenever an element is added, all
elements that were added before have to be removed before
the new element can be invoked.

A double-ended queue (often abbreviated to deque,


pronounced deck) is an abstract data structure that
implements a queue for which elements can only be added
to or removed from the front (head) or back (tail). [1] It is
also often called a head-tail linked list.
This differs from the queue abstract data type or First-InFirst-Out List (FIFO), where elements can only be added to
one end and removed from the other.
8

A linked list is data structure that consists of a sequence of data records such that
in each record there is a field that contains a reference (i.e., a link) to the next record in
the sequence. Linked lists are among the simplest and most common data structures, and
are used to implement many important abstract data structures, such as stacks, queues,
hash tables, symbolic expressions, skip lists, and many more.

A linked list whose nodes contain two fields: an integer value and a link to the next node
In a doubly-linked list, each node contains, besides the next-node link, a second
link field pointing to the previous node in the sequence. The two links may be called
forward(s) and backwards. Linked lists that lack such pointers are said to be simply
linked, or simple linked lists.

A doubly-linked list whose nodes contain three fields: an integer value, the link forward
to the next node, and the link backward to the previous node
A binary tree is a tree data structure in which each node has
at most two children. Typically the child nodes are called left
and right. In type theory, a binary tree with nodes of type A is
defined inductively as TA = . 1 + A . Binary trees
are commonly used to implement binary search trees and
binary heaps

An AVL tree is a self-balancing binary search tree, and it is the


first such data structure to be invented.[1] In an AVL tree, the
A B-tree is a tree data structure that keeps data sorted and
heights of the two child subtrees of any node differ by at most
allows searches, insertions, and deletions in logarithmic
one; therefore, it is also said to be height-balanced. Lookup,
amortized time. Unlike self-balancing binary search trees, it is
insertion, and deletion all take O(log n) time in both the
optimized for systems that read and write large blocks of data.
average and worst cases, where n is the number of nodes in the
It is most commonly used in databases and filesystems.
tree prior to the operation. Insertions and deletions may require
A B-tree of order m (the maximum number of children for each
the tree to be rebalanced by one or more tree rotations.
node) is a tree which satisfies the following properties:
1. Every node has at most m children.
2. Every node (except root and leaves) has at least m2
children.
3. The root has at least two children if it is not a leaf node.
4. All leaves appear in the same level, and carry
information.
5. A non-leaf node with k children contains
9 k1 keys

Cycle I
1. Write a program to demonstrate a class in c++.
2. Write the following programs to demonstrate class templates:
Linear search.
Binary search.
Finding max and min of the set of nos using array.
3. Write a program for Stack using arrays.
4. Write a program for Queue using arrays.
5. Write a program for Circular queue using arrays.
6. Write a program for Dequeue using arrays.
7. Write a program to implement linear list using arrays.

10

//1. prg to print a message using a c++ class.


#include<iostream.h>
class it
{
public:
it()
{
cout<<This program is to demonstrate a class.;
}
};
main()
{
it a;
}
Output:
This program is to demonstrate a class.

11

//2. Write a program to search an element in an array using linear search


technique (use templates).
[TOP]
Implementation logic:
Declare a class with a member function (say getdata()) to accept array elements
and another (say display) to carry out the search process.
getdata():
Accept elements in an array.
cout<<\n Enter array elements;
for(int i=0;i<n;i++)
cin>>a[i];
Accept element to be searched i.e. the key element.
display():
Compare each array element with the key element. If the match is found then set a
variable say b (initially set b to zero) to one and terminate the search. After the
check if the variable b is one the display Element found else display Element not
found
Code:
#include <iostream.h>
template<class T>
class lin
{
T a[10],key;
int i,j,n;
public:
void getdata();
void display();
};
template<class T>
void lin<T>::getdata()
{
cout<<Enter no of array elements<<endl;
cin>>n;
cout<<Enter array elements<<endl;
for(i=0;i<n;i++)
cin>>a[i];
cout<<Enter the element to be searched:
cin>>key;
}
template<class T>
void lin<T>::display()
{
12

int b=0;
for(i=0;i<n;i++)
{
if(a[i]=key)
{
b=1;
break;
}
}
if(b==1)
cout<<Element Found at<<i+1<< position;
else
cout<<Not Found;
}
main()
{
int ch;
cout<<\n Enter 1-for int\n 2-for float\n 3- for char\n;
cin>>ch;
switch(ch)
{
case 1:
{
lin<int>a;
a.getdata();
a.display();
break;
}
case 2:
{
lin<float>a;
a.getdata();
a.display();
break;
}
case 3:
{
lin<char>a;
a.getdata();
a.display();
break;
}
}
}

13

Output:
Enter 1- for int
2- for float
3- for char
1
Enter no of array elements
5
Enter array elements
8
22
5
13
45
Enter element to be searched
13
Element Found at 4 position.

[TOP]

[TOP]

14

// 2.2. Write a program to search an element in an array using binary search


technique (use templates).
[TOP]
Implementation logic:
Declare a class with a constructor and the member functions: sort, display, search.
Accept elements in a Dynamically allocated array via constructor.
a=new T[n];
cout<<\n Enter array elements;
for(int i=0;i<n;i++)
cin>>a[i];
Use sort function to sort elements in an array.
Use display function to display the sorted array.
Use search function to search the desired key element using the following logic:
int l=0,h=size-1,mid;
cout<<Enter element to be searched;
cin>>ele;
while(l<=h)
{
mid=(l+h)/2;
for(i=0;i<size;i++)
{
if(a[mid]==ele)
{
return 1;
break;
}
else if(a[mid]>ele)
h=mid-1;
else
l=mid+1;
}
}
return 0;
Code:
#include<iostream.h>
template<class T>
class bin
{
T *a,ele;
int size,i;
public:
bin();

15

void sort();
void display();
int search();
};
template<class T>
bin<T>::bin()
{
cout<<Enter no of array elements<<endl;
cin>>size;
a=new T[size];
cout<<Enter array elements<<endl;
for(i=0;i<n;i++)
cin>>a[i];
}
template<class T>
void bin<T>::sort()
{
T b;
int j;
for(i=0;i<size;i++)
{
for(j=0;j<size-1;j++)
{
if(a[j]>a[j+1])
{
b=a[j];
a[j]=a[j+1];
a[j+1]=b;
}
}
}
}
template<class T>
void bin<T>::display()
{
cout<<The sorted array is:\n;
for(i=0;i<size;i++)
cout<<a[i]<<endl;
}
template<class T>
void bin<T>::search()
{
int l=0,h=size-1,mid;
cout<<Enter element to be searched;
cin>>ele;
while(l<=h)

16

{
mid=(l+h)/2;
for(i=0;i<size;i++)
{
if(a[mid]==ele)
{
return 1;
break;
}
else if(a[mid]>ele)
h=mid-1;
else
l=mid+1;
}
}
return 0;
}
main()
{
int ch;
cout<<\n Enter 1-for int\n 2-for float\n 3- for char\n;
cin>>ch;
switch(ch)
{
case 1:
{
bin<int>a;
a.sort();
a.display();
int b=a.search();
if(b==1)
cout<<Element Found ;
else
cout<<Element not Found;
break;
}
case 2:
{
bin<float>a;
a.sort();
a.display();
int b=a.search();
if(b==1)
cout<<Element Found ;
else
cout<<Element not Found;

17

break;
}
case 3:
{
bin<char>a;
a.sort();
a.display();
int b=a.search();
if(b==1)
cout<<Element Found ;
else
cout<<Element not Found;
break;
}
}
}
Output:
Enter 1- for int
2- for float
3- for char
3
Enter no of array elements
5
Enter array elements
H
I
M
A
S
The sorted array is:
A
H
I
M
S
Enter element to be searched
A
Element Found.

[TOP]

[TOP]

18

// 2.3. Write a program to find the maximum and minimum no in an array using
templates.
[TOP]
Implementation logic:
Declare a class with a constructor to accept array elements and a member function
to find the max and min number and to display them.
Accept elements in a Dynamically allocated array via constructor.
a=new T[n];
cout<<\n Enter array elements;
for(int i=0;i<n;i++)
cin>>a[i];
Member function details:
Initially assign high and low to first element in an array.
low=a[0];
high=a[0];
Compare high and low with each array element and after each comparison assign
larger value to high and lower value to low.
for(int i=0;i<n;i++)
{
if(high<a[i])
high=a[i];
if(low>a[i])
low=a[i];
}
Code:
#include<iostream.h>
template<class T>
class maxmin
{
T *a;
int n;
public:
maxmin();
void display();
};
template<class T>
maxmin<T>::maxmin()
{
cout<<Enter the size of an array\n;
cin>>n;
a=new T[n];
cout<<\n Enter array elements;
for(int i=0;i<n;i++)

19

cin>>a[i];
}
template<class T>
void maxmin<T>::display()
{
T low,high;
low=a[0];
high=a[0];
for(int i=0;i<n;i++)
{
if(high<a[i])
high=a[i];
if(low>a[i])
low=a[i];
}
cout<<\n The max is <<high<< and the min is <<low;
}
main()
{
int ch;
cout<<Enter 1-for int\n2-for float\n3-for char\n;
cin>>ch;
switch(ch)
{
case 1:
{
maxmin<int> b;
b.display();
break;
}
case2:
{
maxmin<float> b;
b.display();
break;
}
case 3:
{
maxmin<char> b;
b.display();
break;
}
}
}

20

Output:
Enter 1-for int
2- for float
3- for char
1
Enter the size of an array
5
Enter array elements
1 45 23 78 5
The max is 78 and the min is 1

[TOP]

[TOP]

21

//3. Write a program for stack using array.

[TOP]

Implementation logic:
Declare a class with a constructor and the following member functions: push, pop,
display, op.
Dynamically allocate memory to the array via constructor and initialize top to -1 in
it.
a=new T[n];
top=-1;
Member function details:
push(): check if the stack is full if so display stack full else increment top and
push the element in position pointed by the top.
if(top==n-1)// Stack full condition
cout<<stack is full;
else
{
++top;
a[top]=ele;
}
pop(): check if the stack is empty if so display stack empty. No elements to pop
else pop the element pointed by the top, store it in a variable of same type and
decrement top to point the top most element in the stack.
T val;
if(top==-1)
return -1;
else
{
val=a[top];
top--;
return val;
}
Display(): Check if the stack is empty if not display the elements in the stack.
op(): Give the following options to the user:
cout<<\n Enter 1-for push\n 2-for pop\n 3-for display\n 4-to exit\n;
cin>>ch;
Carry out the operation chosen by the user.
Code:
#include<iostream.h>
#include<stdlib.h>
template<class T>
class stack
{
T *a;
22

int n,top;
public:
stack();
void push(T);
T pop();
void display();
void op();
};
template<class T>
stack<T>::stack()
{
cout<<"Enter the no of elements in stack";
cin>>n;
a=new T[n];
top=-1;
}
template<class T>
void stack<T>::push(T ele)
{
if(top==n-1)
cout<<"stack is full";
else
{
++top;
a[top]=ele;
}
}
template<class T>
void stack<T>::display()
{
if(top==-1)
cout<<"\nstack is empty";
else
{
cout<<"\n stack contents are\n";
for(int i=top;i>=0;i--)
cout<<a[i]<<"\t";
}}
template<class T>
T stack<T>::pop()
{
T val;
if(top==-1)
return -1;
else
{

23

val=a[top];
top--;
return val;
}
}
template<class T>
void stack<T>::op()
{
T x;
int ch;
cout<<"\n Enter 1-for push\n 2-for pop\n 3-for display\n 4-to exit\n";
cin>>ch;
while(1)
{
switch(ch)
{
case 1:
{
cout<<"\n Enter element to push";
cin>>x;
push(x);
break;
}
case 2:
{
x=pop();
if(x==-1)
cout<<"\n stack is empty\n";
else
cout<<"Popped value is"<<x<<endl;
break;
}
case 3:
{
display();
break;
}
case 4:
{
exit(0);
}
}
cout<<"\n Enter another choice\n";
cin>>ch;
}
}

24

void main()
{
int ch;
cout<<"\nEnter 1-for int\n2-for float\n3- for char\n";
cin>>ch;
switch(ch)
{
case 1:
{
stack <int> j;
j.op();
break;
}
case 2:
{
stack<float>j;
j.op();
break;
}
case 3:
{
stack<char>j;
j.op();
break;
}
}
}
Output:

[TOP]

Enter 1-for int


2- for float
3- for char
3
Enter the no of elements in stack 4
Enter 1- for push
2- for pop
3- for display
4- for exit
1
Enter element to push a
Enter another choice 1
Enter element to push b
Enter another choice 1
Enter element to push c

25

Enter another choice 2


poped value is c
Enter another choice 3
Stack contents are
b
a
Enter another 4

[TOP]

26

//4. Write a program for queue using arrays.

[TOP]

Implementation logic:
Declare a class with a constructor and the following member functions: enqueue,
dequeue, display, op.
Dynamically allocate memory to the array via constructor and initialize rear=-1 and
front=0 in it.
a=new T[n];
Member function details:
enqueue(): check if the Queue is full if so display Queue full else increment rear
and push the element in position pointed by the rear.
if(r=n-1)/***Queue full condition***/
cout<<Queue is full;
else
{
++r;
a[r]=ele;
}
dequeue(): check If the Queue is empty if so display Queue empty. No element to
pop
Else pop the element pointed by the front, store it in a variable of same type and If
rear and front are pointing to the same position (queue empty) then set them to the
positions show below Else just increment front. Do not forget to return the element.
if(r==-1)/***Queue Empty condition***/
return -1;
else
{
T ele=a[f];
if(f==r)/***Queue Empty***/
{
f=0;r=-1;/*** Set f and r***/
}
else
++f;
return ele;}
Display(): Check If(r==-1) the Queue is empty if not display the elements in it.
op(): Give the following options to the user:
cout<<\n Enter 1-for enqueue\n 2-for dequeue\n 3-for display\n 4-to exit\n;
cin>>ch;
Carry out the operation chosen by the user.

27

Code:
#include<iostream.h>
#include<stdlib.h>
template<class T>
class queue
{
T a[20];
int f,r,n;
public:
queue()
{
f=0;
r=-1;
cout<<"Enter the size of the array";
cin>>n;
}
void enqueue(T);
T dequeue();
void display();
void call();
};
template<class T>
void queue<T>::enqueue(T ele)
{
if(r==n-1)
cout<<"Queue is full";
else
{
++r;
a[r]=ele;
}
}
template<class T>
T queue<T>::dequeue()
{
if(r==-1)
return -1;
else
{
T ele=a[f];
if(f==r)
{
f=0;r=-1;
}
else

28

++f;
return ele;
}
}
template<class T>
void queue<T>::call()
{
int ch;
T x;
cout<<"\nEnter 1-for enqueue\n2-for dequeue\n3-for display\n4-for exit";
cin>>ch;
while(1)
{
switch(ch)
{
case 1:
{
cout<<"\nEnter element ";
cin>>x;
enqueue(x);
break;
}
case 2:
{
x=dequeue();
if(x==-1)
cout<<"\nQueue is empty";
else
cout<<"\nThe front element in the queue is"<<x;
break;
}
case 3:
{
display();
break;
}
case 4:
exit(0);
}
cout<<"\nEnter another choice";
cin>>ch;
}
}
template<class T>
void queue<T>::display()
{

29

if(r==-1)
cout<<"\nQueue is empty";
else
{
cout<<"\ncontents are\n";
for(int i=f;i<=r;i++)
cout<<a[i]<<endl;
}
}
void main()
{
int ch;
cout<<"\nEnter 1-for int\n2-for float\n3-for char";
cin>>ch;
switch(ch)
{
case 1:
{
queue<int>a;
a.call();
break;
}
case 2:
{
queue<float>a;
a.call();
break;
}
case 3:
{
queue<char>a;
a.call();
break;
}
}
}
Output:
Enter 1-for int
2-for float
3-for char
3
Enter the size of the array: 4
Enter 1-for enqueue
2-for dequeue
3-for display

[TOP]

30

4-for exit
1
Enter element j
Enter another choice 1
Enter element a
Enter another choice 2
The front element in the queue is j
Enter another choice 3
Contents are
a
Enter another choice 4

31

//5. Write a program for circular Queue using arrays.

[TOP]

Implementation logic:
Declare a class with a constructor and the following member functions: enqueue,
dequeue, display, op.
Dynamically allocate memory to the array via constructor and initialize rear and
front to -1 in it.
a=new T[n];
Member function details:
enqueue(): check If the Circular queue is full if so display Queue full Else assign
rear to (rear+1)%n and push the element in position pointed by the rear.
If front is equal to -1 then set it to 0.
if((r+1)%n=f)/***Circular queue full condition***/
cout<<Queue is full;
else
{
r=(r+1)%n;
a[r]=ele;
}
if(f==-1)
f=0;
dequeue(): check If the Queue is empty if so display Queue empty. No element to
pop
Else pop the element pointed by the front i.e. store it in a variable of same type and If
rear and front are pointing to the same position (queue empty) then set them to the
positions show below Else just assign (f+1)%n to front . Do not forget to return the
element.
if(r==-1)/***Circular queue Empty condition***/
return -1;
else
{
T ele=a[f];
if(f==r)/***Circular queue Empty***/
f=r=-1;
else
f=(f+1)%n;
return ele;
Display(): Check If(r==-1||f==-1) the Circular queue is empty if not check
If front is less than or equal to rear if so display elements present at the indices
starting from front to rear.
If front is greater than rear then display elements that are
1. Present at the indices starting from front to n-1(n is size of the array).
2. Present at the indices starting from 0 to rear.

32

int i;
if(r==-1|| f==-1)
cout<<"\nQueue is empty";
else
{
cout<<"\ncontents are\n";
if(f<=r)
{
for(i=f;i<=r;i++)
cout<<a[i]<<endl;
}
if(f>r)
{
for(i=f;i<=n-1;i++)
cout<<a[i]<<endl;
for(i=0;i<=r;i++)
cout<<a[i]<<endl;
}
}
op(): Give the following options to the user:
cout<<\n Enter 1-for enqueue\n 2-for dequeue\n 3-for display\n 4-to exit\n;
cin>>ch;
Carry out the operation chosen by the user.
Code:
#include<iostream.h>
#include<stdlib.h>
template<class T>
class cqueue
{
T a[20];
int f,r,n;
public:
cqueue()
{
f=r=-1;
cout<<"Enter the size of the array";
cin>>n;
}
void enqueue(T);
T dequeue();
void display();
T call();
};
template<class T>

33

void cqueue<T>::enqueue(T ele)


{
if((r+1)%n==f)
cout<<"Queue is full";
else
{
r=(r+1)%n;
a[r]=ele;
}
if(f==-1)
f=0;
}
template<class T>
T cqueue<T>::dequeue()
{
T ele;
if(f==-1)
return -1;
else
{
ele=a[f];
}
if(f==r)
f=r=-1;
else
f=(f+1)%n;
return ele;
}
template<class T>
T cqueue<T>::call()
{
int ch;
T x;
cout<<"\nEnter 1-for enqueue\n2-for dequeue\n3-for display\n4-for exit";
cin>>ch;
while(1)
{
switch(ch)
{
case 1:
{
cout<<"\nEnter element";
cin>>x;
enqueue(x);
break;
}

34

case 2:
{
x=dequeue();
if(x==-1)
cout<<"\nQueue is empty";
else
cout<<"\nThe front element in the queue is"<<x;
break;
}
case 3:
{
display();
break;
}
case 4:
exit(0);
}
cout<<"\nEnter another choice";
cin>>ch;
}
}
template<class T>
void cqueue<T>::display()
{
int i;
if(r==-1|| f==-1)
cout<<"\nQueue is empty";
else
{
cout<<"\ncontents are\n";
if(f<=r)
{
for(i=f;i<=r;i++)
cout<<a[i]<<endl;
}
if(f>r)
{
for(i=f;i<=n-1;i++)
cout<<a[i]<<endl;
for(i=0;i<=r;i++)
cout<<a[i]<<endl;
}
}
}
void main()
{

35

int ch;
cout<<"\nEnter 1-for int\n2-for float\n3-for char\n";
cin>>ch;
switch(ch)
{
case 1:
{
cqueue<int>a;
a.call();
break;
}
case 2:
{
cqueue<float>a;
a.call();
break;
}
case 3:
{
cqueue<char>a;
a.call();
break;
}
}
}
Output:
Enter 1-for int
2-for float
3-for char
1
Enter the size of the array: 4
Enter 1-for enqueue
2-for dequeue
3-for display
4-for exit
1
Enter element 12
Enter another choice 1
Enter element 23
Enter another choice 3
Contents are
12
23
Enter another choice 2
The front element in the queue is 12

[TOP]

36

Enter another choice 4


//6. Write a program for dequeue using arrays.

[TOP]

Implementation logic:
Declare a class with a constructor and the following member functions: enqueue,
dequeue, display, op.
Dynamically allocate memory to the array via constructor and initialize rear and
front to -1 in it.
a=new T[n];
Member function details:
enqueue-f(): check If the dequeue is full if so display dequeue full Else
If f==0 push the element in position pointed by the front and assign front to n-1
Else push the element in position pointed by the front & assign front to front-1
if((r+1)%n==f)/***Dequeue full condition***/
cout<<Queue is full;
else if(f==0)
{
a[f]=ele;
f=n-1;
}
else
{
a[f]=ele;
f=f-1;
}
enqueue-r():check If the dequeue is full if so display dequeue full Else
Assign rear to (rear+1)%n and push the element in position pointed by the rear
if((r+1)%n==f) /***Dequeue full condition***/
cout<<deque is full;
else
{
r=(r+1)%n;
a[r]=ele;
}
dequeue-f(): check If the Queue is empty if so display Queue empty. No element
to pop
Else
If (f+1)%n==r then pop the element pointed by the (f+1)%n i.e. store it in a variable
of same type and set front and rear to 0.
Else pop the element pointed by the (f+1)%n i.e. store it in a variable of same type
and just assign (f+1)%n to front . Do not forget to return the element.
if(f==0&& r==0)/***Circular queue Empty condition***/
return -1;
else if((f+1)%n==r)
{
ele=a[(f+1)%n];

37

f=r=0;
}
else
{
ele=a[(f+1)%n];
f=(f+1)%n;
}
return ele;
dequeue-r(): check If the Queue is empty if so display Queue empty. No element
to pop
Else pop the element pointed by the (f+1)%n i.e. store it in a variable of same type
and If (f+1)%n==r then set front and rear to 0.
Else If r==0 then assign n-1 to rear Else assign rear-1 to rear. Do not forget to return
the element.
if(f==0&& r==0)/***Dequeue empty condition***/
return -1;
else
{
ele=a[r];
if((f+1)%n==r)
f=r=0;
else if(r==0)
r=n-1;
else
r=r-1;
}
return ele;
Display(): Check If(r==0&&f==0) the dequeue is empty if not check
If front is less than or equal to rear if so display elements present at the indices
starting from front+1 to rear.
If front is greater than rear then display elements that are
1. Present at the indices starting from front+1 to n-1(n is size of the array).
2. Present at the indices starting from 0 to rear.
if(r==0&& f==0)
cout<<\ndeque is empty;
else
{
cout<<\ncontents are\n;
if(f<=r)
{
for(int i=f+1;i<=r;i++)
cout<<a[i]<<endl;
}
else if(f>r)
{
for(int i=f+1;i<=n-1;i++)

38

cout<<a[i]<<endl;
for(int i=0;i<r;i++)
cout<<a[i]<<endl;
}
}
op(): Give the following options to the user:
cout<<\n Enter 1-for enqueue-f\n 2-for enqueue-r\n3-for dequeue-f\n4-for dequeuer\n5-for display\n 6-to exit\n;
cin>>ch;
Carry out the operation chosen by the user.
Code:
#include<iostream.h>
template<class T>
class deque
{
T a[20];
int f,r,n;
public:
deque()
{
f=r=0;
cout<<Enter the size of the array;
cin>>n;
}
void enf(T);
void enr(T);
T def();
T der();
void display();
T call();
};
template<class T>
void deque<T>:enf(T ele)
{
if((r+1)%n==f)
cout<<Queue is full;
else if(f==0)
{
a[f]=ele;
f=n-1;
}
else
{
a[f]=y;

39

f=f-1;
}
}
template<class T>
void deque<T>:enr(T ele)
{
if((r+1)%n==f)
cout<<deque is full;
else
{
r=(r+1)%n;
a[r]=ele;
}
}
template<class T>
T deque<T>::def()
{
T ele;
if(f==0&& r==0)
return -1;
else if((f+1)%n==r)
{
ele=a[(f+1)%n];
f=r=0;
}
else
{
ele=a[(f+1)%n];
f=(f+1)%n;
}
return ele;
}
template<class T>
T deque<T>::der()
{
T ele;
if(f==0&& r==0)
return -1;
else
{
ele=a[r];
if((f+1)%n==r)
f=r=0;
else if(r==0)
r=n-1;

40

else
r=r-1;
}
return ele;
}
template<class T>
void deque<T>::call()
{
int ch;
T x;
cout<<\nEnter 1-for enqueue-f\n2-for enqueue-r\n3-for dequeue-f\n4-for dequeuer\n5-for display\n6-for exit;
cin>>ch;
while(1)
{
switch(ch)
{
case 1:
{
cout<<\nEnter element ;
cin>>x;
enf(x);
break;
}
case 2:
{
cout<<\nEnter element ;
cin>>x;
enr(x);
break;
}
case 3:
{
x=def();
if(x==-1)
cout<<\nDeque is empty;
else
cout<<\nThe element in the deque is<<x;
break;
}
case 4:
{
x=der();
if(x==-1)
cout<<\ndeque is empty;
else

41

cout<<\nThe element in the deque is<<x;


break;
}
case 5:
{
display();
break;
}
case 6:
exit(0);
}
cout<<\nEnter another choice;
cin>>ch;
}
}
template<class T>
void deque<T>::display()
{
if(r==0&& f==0)
cout<<\ndeque is empty;
else
{
cout<<\ncontents are\n;
if(f<=r)
{
for(int i=f+1;i<=r;i++)
cout<<a[i]<<endl;
}
else if(f>r)
{
for(int i=f+1;i<=n-1;i++)
cout<<a[i]<<endl;
for(int i=0;i<r;i++)
cout<<a[i]<<endl;
}
}
}
main()
{
int ch;
cout<<\nEnter 1-for int\n2-for float\n3-for char\n;
cin>>ch;
switch(ch)
{
case 1:
{

42

deque<int>a;
a.call();
break;
}
case 2:
{
deque<float>a;
a.call();
break;
}
case 3:
{
deque<char>a;
a.call();
break;
}
}
}
Output:
Enter 1-for int
2-for float
3-for char
1
Enter the size of the array: 4
Enter 1-for enqueue-f
2-for enqueue-r
3-for dequeue-f
4-for dequeue-r
5-for display
6-for exit
1
Enter element 12
Enter another choice 2
Enter element 23
Enter another choice 1
Enter element 30
Enter another choice 2
Enter element 45
Dequeue is full
Enter another choice 3
The element in the deque is 30
Enter another choice 4
The element in the deque is 20
Enter another choice 5
Contents are

[TOP]

43

12
Enter another choice 6
//7. Write a program for linear list using arrays.

[TOP]

Implementation logic:
Initially assign lintsize n=0.
Define a member function empty() to check for the empty list and a Member
function size() to find the no of elements in the list.
get(index): This member function returns an element if present at the given index
of the list else a false value is returned.
indexof(x): This member function returns the index of the element x and returns a
false value if x is not present in the list.
erase(index): This member function removes or deletes the index element.
To remove or delete this element we first need to ascertain that the list contains an
element with this index and then delete the element.
insert(index,x): This member function inserts an element x as the index element.
To insert new element as index element we first need to move element at position
index through n-1 one position up then insert new element in position index and
increment n by one.
Code:
#include<iostream.h>
#include<stdlib.h>
template<class T>
class linlist
{
T *a;
int l,n;
public:
linlist();
~linlist();
int empty();
int size();
T get(int);
int indexof(T);
void erase(int);
void insert(T,int);
void output();
int checkindex(int);
void op();
};
template<class T>
linlist<T>::linlist()
{
cout<<"\nEnter length of array";
cin>>l;
44

a=new T[l];
n=0;
}
template<class T>
linlist<T>::~linlist()
{
delete []a;
}
template<class T>
int linlist<T>::empty()
{
if(n==0)
return 1;
else
return 0;
}
template<class T>
int linlist<T>::size()
{
return n;
}
template<class T>
int linlist<T>::checkindex(int index)
{
if(index<0||index>l)
return 1;
else
return 0;
}
template<class T>
T linlist<T>::get(int index)
{
if(checkindex(index)==1)
return -1;
else
return a[index];
}
template<class T>
int linlist<T>::indexof(T ele)
{
int i;
for(i=0;i<l;i++)
{
if(a[i]==ele)
return i;
}

45

return -1;
}
template<class T>
void linlist<T>::erase(int index)
{
int i;
if(checkindex(index)==1)
cout<<"\nInvlaid index";
else
{
for(i=index;i<n-1;i++)
a[i]=a[i+1];
n--;
}
}
template<class T>
void linlist<T>::insert(T ele,int index)
{
int i;
if(checkindex(index)==1)
cout<<"\nInvalid index";
else if(n==l)
{
cout<<"\nList is full";
return;
}
else
{
for(i=n;i>index;i--)
a[i]=a[i-1];
a[index]=ele;
n++;
}
}
template<class T>
void linlist<T>::output()
{
int i;
for(i=0;i<n;i++)
cout<<endl<<a[i];
}
template<class T>
void linlist<T>::op()
{
T ele;
int ch,index;

46

cout<<"\nEnter 1.To insert element\n2.To erase element\n3.To print list size\n4.To get
index of given element\n5.To get element's index \n6.Exit \n7.Display";
cin>>ch;
while(1)
{
switch(ch)
{
case 1:
{
cout<<"\nEnter index";
cin>>index;
cout<<"Enter element to be inserted in the list";
cin>>ele;
insert(ele,index);
break;
}
case 2:
{
cout<<"\nEnter the index at which element to be deleted";
cin>>index;
erase(index);
break;
}
case 3:
{
index=size();
cout<<"\nThe size of the list is"<<index;
break;
}
case 4:
{
int x;
cout<<"\nEnter element to find its index";
cin>>ele;
x=indexof(ele);
if(x==-1)
cout<<"\n Element is not in the list";
else
cout<<"\nThe index of element is"<<x;
break;
}
case 5:
{
T x;
cout<<"\nEnter index to find the element";
cin>>index;

47

x=get(index);
if(x==-1)
cout<<"\nGiven index is out of bound";
else
cout<<"\nThe element at the given index is "<<x;
break;
}
case 6:
exit(0);
case 7:
{
output();
break;
}
}
cout<<"\nEnter another choice";
cin>>ch;
}
}
void main()
{
int ch;
cout<<"\nEnter 1.for int\n2.for float\n3.for char";
cin>>ch;
switch(ch)
{
case 1:
{
linlist<int>j;
j.op();
break;
}
case 2:
{
linlist<float>j;
j.op();
break;
}
case 3:
{
linlist<char>j;
j.op();
break;
}
}
}

48

Output:

[TOP]

Enter 1-for int


2-for float
3-for char
1
Enter length of array 4
Enter 1.To insert element
2.To erase element
3.To print listsize
4.To get index of given element
5.To get elements index
6.Exit
7.Display 1
Enter index and element to be inserted in the list 0
12
Enter another choice 1
Enter index and element to be inserted in the list 1
23
Enter another choice 1
Enter index and element to be inserted in the list 2
45
Enter another choice 2
Enter index at which element to be deleted 2
Enter another choice 3
The size of the list is 2
Enter another choice 4
Enter element to find its index 23
The index of the element is 1
Enter another choice 5
Enter index to find the element 0
The element at the given index is 12
Enter another choice 7
12
23
Enter another choice 6

[TOP]

49

Cycle II
1. Write a program to implement single linked list.
2. Write a program to implement Stack using linked list.
3. Write a program to implement Queue using linked list.
4. Write a program to implement Double linked list.
5. Write a program for polynomial arithmetic using linked list.
6. Write a program to convert UN parenthesized infix to postfix.
7. Write a program to convert parenthesized infix to postfix.
8. Write a program to evaluate a postfix expression.

50

//1. Write a program to implement single link list.

[TOP2]

Implementation logic:
Declare a structure node containing a template type ele and a pointer of type
structure which is declared.
struct node
{
T info;
node *next;
};
Initially assign head=tail=NULL.
Member Functions details:
prepend(ele): Allocate memory dynamically for new node new1. Assign the
element to be inserted to info field of the node new1 and assign the pointer head to
next field of the node new1. If head is pointing to NULL (i.e. check for empty link
list) make tail point to new1. Assign new1 to head.
node<T>*new1;
new1=new node<T>;
if(new1!=NULL)
{
new1->info=n;
new1->next=head;
}
if(head==NULL)
{
tail=new1;
}
head=new1;
append(ele): Allocate memory dynamically for new node new1. Assign the
element to be inserted to info field of the node new1 and assign NULL to next field of
the node new1. If head is pointing to NULL (i.e. check for empty link list) make it
point to new1 Else assign new1 to next of tail and make tail point to new1.
node<T>*new1;
new1=new node<T>;
if(new1!=NULL)
{
new1->info=n;
new1->next=NULL;
}
if(head==NULL)
head=new1;
else
tail->next=new1;

51

tail=new1;
insaft(ptr,ele): Allocate memory dynamically for new node new1. Assign the
element to be inserted to info field of the node new1 and assign next of ptr to next of
the node new1. Assign new1 to next of ptr. If tail equal to ptr assign new1 to tail.
node<T>*new1;
new1=new node<T>;
if(new1!=NULL)
{
new1->info=n;
new1->next=ptr->next;
}
ptr->next=new1;
if(tail==ptr)
tail=new1;
insbef(ptr,ele): Allocate memory dynamically for new node new1 and prev. Assign
the element to be inserted to info field of the node new1 and assign ptr to next of the
node new1. check if inserting before the first element otherwise search for node
before ptr to set links.
node<T>*new1;
node<T>*prev;
if(new1!=NULL)
{
new1->info=n;
new1->next=ptr;
}
if(head==ptr)
head=new1;
else
{
prev=head ;
while(prev!=NULL&&prev->next!=ptr)//checking for first node
prev=prev->next; //setting the links
prev->next=new1;
}
del (ele): Make the temporary node point to head and assign prev node to NULL.
Search for element to be deleted by moving temp until it points to the node which is
to be deleted. If it is not found (i.e. temp=NULL) display item not found. If first ele is
to be deleted then do not forget to assign next of temp (i.e. next ele) to head. Else let
next of temp point to next of prev (i.e. deleting the element by losing its track or
removing its address). If last ele is to be deleted then make tail point to the prev
element. Deallocated memory for temp.
temp=head;
prev=NULL;
while(temp!=NULL&&temp->info!=ele)
{
prev=temp;

52

temp=temp->next;
}
if(temp==NULL)
cout<<\nItem not found for deleting;
if(temp==head)
head=temp->next;
else
prev->next=temp->next;
if(temp==tail)
tail=prev;
delete temp;
Search(ele): Assign head to temporary node. Traverse the list in search of the node
till info of temp is not equal to the element and next of temp is not equal to NULL
temp=head;
while(temp->info!=n&&temp->next!=NULL)
temp=temp->next;
if(temp->info==n)
return temp;
Code:
#include<iostream.h>
#include<stdlib.h>
template<class T>
struct node
{
T info;
node *next;
};
template <class T>
class list
{
node<T>*head,*tail;
public:
list()
{
head=tail=NULL;
}
~list();
void append(T);
void prepend(T);
void insaft(node<T>*,T);
void insbef(node<T>*,T);
void del(T);
node<T>*search(T);
void display();

53

void op();
};
template<class T>
void list<T>::prepend(T n)
{
node<T>*new1;
new1=new node<T>;
if(new1!=NULL)
{
new1->info=n;
new1->next=head;
}
if(head==NULL)
{
tail=new1;
}
head=new1;
}
template<class T>
void list<T>::append(T n)
{
node<T>*new1;
new1=new node<T>;
if(new1!=NULL)
{
new1->info=n;
new1->next=NULL;
}
if(head==NULL)
head=new1;
else
tail->next=new1;
tail=new1;
}
template<class T>
void list<T>::insaft(node<T>*ptr,T n)
{
node<T>*new1;
new1=new node<T>;
if(new1!=NULL)
{
new1->info=n;
new1->next=ptr->next;
}
ptr->next=new1;
if(tail==ptr)

54

tail=new1;
}
template<class T>
void list<T>::insbef(node<T>*ptr,T n)
{
node<T>*new1;
new1=new node<T>;
node<T>*prev;
if(new1!=NULL)
{
new1->info=n;
new1->next=ptr;
}
if(head==ptr)
head=new1;
else
{
prev=head ;
while(prev!=NULL&&prev->next!=ptr)
prev=prev->next;
prev->next=new1;
}
}
template<class T>
void list<T>::del(T n)
{
node<T>*temp;
node<T>*prev;
temp=head;
prev=NULL;
while(temp!=NULL&&temp->info!=n)
{
prev=temp;
temp=temp->next;
}
if(temp==NULL)
cout<<"\nItem not found for deleting";
if(temp==head)
head=temp->next;
else
prev->next=temp->next;
if(temp==tail)
tail=prev;
delete temp;
}
template<class T>

55

node<T>* list<T>::search(T n)
{
node<T>*temp;
temp=head;
while(temp->info!=n&&temp->next!=NULL)
temp=temp->next;
if(temp->info==n)
return temp;
}
template<class T>
void list<T>::display()
{
node<T>*temp;
temp=head;
while(temp!=NULL)
{
cout<<endl<<temp->info;
temp=temp->next;
}
}
template<class T>
list<T>::~list()
{
node<T>*temp;
while(head!=NULL)
{
temp=head;
head=head->next;
delete temp;
}
tail=NULL;
}
template<class T>
void list<T>::op()
{
int ch;
cout<<"\nEnter 1.To prepend\n2.To append\n3.To insert before a particular
pointer\n4.To insert element after a particular pointer\n5.Delete element from the
list\n6.Display\n7.Exit";
cin>>ch;
while(1)
{
switch(ch)
{
case 1:
{

56

T n;
cout<<"\nEnter element to insert in the list";
cin>>n;
prepend(n);
break;
}
case 2:
{
T n;
cout<<"\nEnter element to insert in the list";
cin>>n;
append(n);
break;
}
case 3:
{
node<T>*ptr;
T n,ele;
cout<<"\nEnter element to be searched";
cin>>n;
ptr=search(n);
cout<<"\nEnter element to be inserted before the desired pointer";
cin>>ele;
insbef(ptr,ele);
break;
}
case 4:
{
node<T>*ptr;
T n,ele;
cout<<"\nEnter element to be searched";
cin>>n;
ptr=search(n);
cout<<"\nEnter element to be inserted after the desired pointer";
cin>>ele;
insaft(ptr,ele);
break;
}
case 5:
{
T n;
cout<<"\nEnter element to be searched";
cin>>n;
del(n);
break;
}

57

case 6:
{
display();
break;
}
case 7:
{
exit(0);
}
}
cout<<"\nEnter another choice";
cin>>ch;
}
}
void main()
{
int ch;
cout<<"\nEnter 1.For int\n2.For float\n3.For char";
cin>>ch;
switch(ch)
{
case 1:
{
list<int>j;
j.op();
break;
}
case 2:
{
list<float>j;
j.op();
break;}
case 3:
{
list<char>j;
j.op();
break;}}}
Output:

[TOP2]

Enter 1-For int


2-For float
3-For char 1
Enter 1.To prepend
2.To append

58

3.To insert before a particular pointer


4.To insert after a particular pointer
5.Delete element from the list
6.Display
7.Exit
1
Enter element to insert in the list 12
Enter another choice 2
Enter element to insert in the list 23
Enter another choice 3
Enter element to be searched 23
Enter element to insert before the desired pointer 36
Enter another choice 4
Enter element to be searched 12
Enter element to insert after the desired pointer 54
Enter another choice 5
Enter element to be deleted 54
Enter another choice 6
12
36
23
Enter another choice 7

59

[TOP2]

//2. Write a program to implement linked stack.

[TOP2]

Implementation logic:
Declare a structure node containing a template type ele and a pointer of type
structure which is declared.
struct node
{
T info;
node *next;
};
Initially assign top=NULL.
Member Functions details:
push(ele): Allocate memory dynamically for new node new1. Assign the element
to be inserted to info field of the node new1 and assign the pointer top to next field of
the node new1. Make top point to new1.
node<T>*new1;
new1=new node<T>;
if(new1!=NULL)
{
new1->info=ele;
new1->next=top;
}
top=new1;
pop(): Check If stack is empty Else assign top to temp and store value of temp (i.e.
info) in a variable of same type and make top point to its next. Delete the temporary
node and return the value in the variable.
if(top==NULL)
return -1;
else
{
temp=top;
val=temp->info;
top=top->next;
delete temp;
return val;
}
Code:
#include<iostream.h>
#include<stdlib.h>
template<class T>
struct node
{

60

T info;
node *next;
};
template<class T>
class linstack
{
node<T>*top;
public:
linstack()
{
top=NULL;
}
void push(T);
T pop();
void display();
void call();
};
template<class T>
void linstack<T>::push(T ele)
{
node<T>*new1;
new1=new node<T>;
if(new1!=NULL)
{
new1->info=ele;
new1->next=top;
}
top=new1;
}
template<class T>
T linstack<T>::pop()
{
T val;
node<T>*temp;
if(top==NULL)
return -1;
else
{
temp=top;
val=temp->info;
top=top->next;
delete temp;
return val;
}
}
template<class T>

61

void linstack<T>::call()
{
int ch;
T x;
cout<<"\nEnter 1-for push\n2-for pop\n3-for display\n4-exit";
cin>>ch;
while(1)
{
switch(ch)
{
case 1:
{
cout<<"\nEnter element to push";
cin>>x;
push(x);
break;
}
case 2:
{
x=pop();
if(x==-1)
cout<<"\nstack is empty";
else
cout<<"\nThe top element in the stack is"<<x;
break;
}
case 3:
{
display();
break;
}
case 4:
exit(0);
}
cout<<"\nEnter another choice";
cin>>ch;
}
}
template<class T>
void linstack<T>::display()
{
node<T>*temp;
temp=top;
cout<<"\ncontents are\n";
while(temp!=NULL)
{

62

cout<<temp->info<<endl;
temp=temp->next;
}
}
void main()
{
int ch;
cout<<"\nEnter 1-for int\n2-for float\n3-for char";
cin>>ch;
switch(ch)
{
case 1:
{
linstack<int>a;
a.call();
break;
}
case 2:
{
linstack<float>a;
a.call();
break;
}
case 3:
{
linstack<char>a;
a.call();
break;
}
}
}
Output:
Enter 1-for int
2-for float
3-for char
1
Enter 1-for push
2-for pop
3-for display
4-exit
1
Enter element to push 12
Enter another choice 1
Enter element to push 23

[TOP2]

63

Enter another choice 1


Enter element to push 36
Enter another choice 2
The top element in the stack is 36
Enter another choice 3
Contents are
23
12
Enter another choice 4

[TOP2]

64

//3. Write a program to implement linked queue.

[TOP2]

Implementation logic:
Declare a structure node containing a template type ele and a pointer of type
structure which is declared.
struct node
{
T info;
node *next;
};
Initially assign rear=front=NULL.
Member Functions details:
enqueue(ele): Allocate memory dynamically for new node new1. Assign the
element to be inserted to info field of the node new1 and assign the NULL to next
field of the node new1. If rear =NULL (i.e. empty queue) make front point to new1.
Else make next of rear point to new1 and rear point to new1.
node<T>*new1;
new1=new node<T>;
if(new1!=NULL)
{
new1->info=ele;
new1->next=NULL;
}
if(rear==NULL)
front=new1;
else
rear->next=new1;
rear=new1;
dequeue(): Check If queue is empty Else assign front to temp and store value of
temp (i.e. info) in a variable of same type. Check If queue becomes empty if so assign
front and rear to NULL else make front point to its next. Delete the temporary node
and return the value in the variable.
T val;
if(front==NULL)
return -1;
else
{
node<T>*temp;
temp=front;
val=temp->info;
if(front==rear)
front=rear=NULL;

65

else
front=front->next;
delete temp;
return val;}
Code:
#include<iostream.h>
#include<stdlib.h>
template<class T>
struct node
{
T info;
node *next;
};
template<class T>
class linqueue
{
node<T>*rear,*front;
public:
linqueue()
{
rear=front=NULL;
}
void enqueue(T);
T dequeue();
void display();
void call();
};
template<class T>
void linqueue<T>::enqueue(T ele)
{
node<T>*new1;
new1=new node<T>;
if(new1!=NULL)
{
new1->info=ele;
new1->next=NULL;
}
if(rear==NULL)
front=new1;
else
rear->next=new1;
rear=new1;
}
template<class T>
T linqueue<T>::dequeue()
{

66

T val;
if(front==NULL)
return -1;
else
{
node<T>*temp;
temp=front;
val=temp->info;
if(front==rear)
front=rear=NULL;
else
front=front->next;
delete temp;
return val;
}
}
template<class T>
void linqueue<T>::call()
{
int ch;
T x;
cout<<"\nEnter 1-for enqueue\n2-for dequeue\n3-for display\n4-for exit";
cin>>ch;
while(1)
{
switch(ch)
{
case 1:
{
cout<<"\nEnter element ";
cin>>x;
enqueue(x);
break;
}
case 2:
{
x=dequeue();
if(x==-1)
cout<<"\nQueue is empty";
else
cout<<"\nThe front element in the queue is"<<x;
break;
}
case 3:
{
display();

67

break;
}
case 4:
exit(0);
}
cout<<"\nEnter another choice";
cin>>ch;
}
}
template<class T>
void linqueue<T>::display()
{
if(front==NULL&&rear==NULL)
cout<<"\nQueue is empty";
else
{
node<T>*temp;
temp=front;
cout<<"\ncontents are\n";
while(temp!=NULL)
{
cout<<temp->info<<endl;
temp=temp->next;
}
}
}
void main()
{
int ch;
cout<<"\nEnter 1-for int\n2-for float\n3-for char";
cin>>ch;
switch(ch)
{
case 1:
{
linqueue<int>a;
a.call();
break;
}
case 2:
{
linqueue<float>a;
a.call();
break;
}
case 3:

68

{
linqueue<char>a;
a.call();
break;
}
}
}
Output:
Enter 1-for int
2-for float
3-for char
1
Enter 1-for enqueue
2-for dequeue
3-for display
4-for exit
1
Enter element 12
Enter another choice 1
Enter element 23
Enter another choice 1
Enter element 36
Enter another choice 2
The front element in the queue is 36
Enter another choice 3
Contents are
23
12
Enter another choice 4

[TOP2]

[TOP2]

69

//4. Write a program to implement double linked list.

[TOP2]

Implementation logic:
Declare a structure node containing a template type ele and a pointer of type
structure which is declared.
struct node
{
T info;
node *next;
};
Initially assign head=tail=NULL.
Member Functions details:
prepend(ele): Allocate memory dynamically for new node new1. Assign the
element to be inserted to info field of the node new1, assign NULL to left pointer and
assign the pointer head to right pointer of the node new1. node<T>*new1;
new1=new node<T>;
if(new1!=NULL)
{
new1->info=ele;
new1->lptr=NULL;
new1->rptr=head;
}
If head is pointing to NULL (i.e. check for empty link list) make tail point to new1.
Else make left of head point to new1.
if(head==NULL)
tail=new1;
else
head->lptr=new1;
Assign new1 to head
head=new1;
append(ele): Allocate memory dynamically for new node new1. Assign the
element to be inserted to info field of the node new1, assign NULL to right pointer
and assign the pointer tail to left pointer of the node new1.
node<T>*new1;
new1=new node<T>;
if(new1!=NULL)
{
new1->info=ele;
new1->lptr=tail;
new1->rptr=NULL;
}

70

If head is pointing to NULL (i.e. check for empty link list) make it point to new1.
Else make right of tail point to new1.
if(head==NULL)
head=new1;
else
tail->rptr=new1;
Assign new1 to tail.
tail=new1;
insaft(ptr,ele): Allocate memory dynamically for new node new1. Assign the
element to be inserted to info field of the node new1, assign NULL to right pointer
and assign the ptr to left pointer of the node new1.
node<T>*new1;
new1=new node<T>;
if(new1!=NULL)
{
new1->info=ele;
new1->lptr=ptr;
new1->rptr=NULL;
}
check if inserting at the end of list
if(tail==ptr)
{
tail=rptr=new1;
tail=new1;
}
else
{
new1->rptr=ptr->rptr;
(new1->rptr)->lptr=new1;
ptr->rptr=new1;
}
insbef(ptr,ele): Allocate memory dynamically for new node new1. Initialize next
and info fields of new1
node<T>*new1;
node<T>*prev;
if(new1!=NULL)
{
new1->info=n;
new1->next=ptr;
}
check if inserting at the starting of the list
if(head==ptr)
head=new1;
else
{
prev=head ;

71

while(prev!=NULL&&prev->next!=ptr)//checking for first node


prev=prev->next; //setting the links
prev->next=new1;
}
del (ele): Check if only one node in linked list.
if(head==tail&&head==ptr)
head=tail=NULL;
else
{
//check if first node is to be deleted
if(ptr==head)
{
head=head->rptr;
head->lptr=NULL;
}
else if(ptr==tail)//check if last node is to be deleted
{
tail=tail->lptr;
tail->rptr=NULL;
}
else
{
(ptr->lptr)->rptr=ptr->rptr;
(ptr->rptr)->lptr=ptr->lptr;
}
}
delete ptr; //deallocate memory for ptr.
Search(ele): Assign head to temporary node. Traverse the list in search of the node
till info of temp is not equal to the element and right of temp is not equal to NULL
temp=head;
while(temp->info!=ele&&temp->rptr!=NULL)
temp=temp->rptr;
if(temp->info==ele)
return temp;
Code:
#include<iostream.h>
#include<stdlib.h>
template<class T>
struct node
{
T info;
node *lptr,*rptr;
};
template <class T>

72

class dll
{
node<T>*head,*tail;
public:
dll()
{
head=tail=NULL;
}
void append(T);
void prepend(T);
void insaft(node<T>*,T);
void insbef(node<T>*,T);
void ext(node<T>*);
node<T>*search(T);
void display();
void op();
};
template<class T>
void dll<T>::prepend(T ele)
{
node<T>*new1;
new1=new node<T>;
if(new1!=NULL)
{
new1->info=ele;
new1->lptr=NULL;
new1->rptr=head;
}
if(head==NULL)
tail=new1;
else
head->lptr=new1;
head=new1;
}
template<class T>
void dll<T>::append(T ele)
{
node<T>*new1;
new1=new node<T>;
if(new1!=NULL)
{
new1->info=ele;
new1->lptr=tail;
new1->rptr=NULL;
}
if(head==NULL)

73

head=new1;
else
tail->rptr=new1;
tail=new1;
}
template<class T>
void dll<T>::insaft(node<T>*ptr,T ele)
{
node<T>*new1;
new1=new node<T>;
if(new1!=NULL)
{
new1->info=ele;
new1->lptr=ptr;
new1->rptr=NULL;
}
if(tail==ptr)
{
tail->rptr=new1;
tail=new1;
}
else
{
new1->rptr=ptr->rptr;
(new1->rptr)->lptr=new1;
ptr->rptr=new1;
}
}
template<class T>
void dll<T>::insbef(node<T>*ptr,T ele)
{
node<T>*new1;
new1=new node<T>;
if(new1!=NULL)
{
new1->info=ele;
new1->lptr=NULL;
new1->rptr=ptr;
}
if(head==ptr)
{
head->lptr=new1;
head=new1;
}
else
{

74

new1->lptr=ptr->lptr;
ptr->lptr=new1;
(new1->lptr)->rptr=new1;
}
}
template<class T>
void dll<T>::ext(node<T> *ptr)
{
if(head==tail&&head==ptr)
head=tail=NULL;
else
{
if(ptr==head)
{
head=head->rptr;
head->lptr=NULL;
}
else if(ptr==tail)
{
tail=tail->lptr;
tail->rptr=NULL;
}
else
{
(ptr->lptr)->rptr=ptr->rptr;
(ptr->rptr)->lptr=ptr->lptr;
}
}
delete ptr;
}
template<class T>
node<T>*dll<T>::search(T ele)
{
node<T>*temp;
temp=head;
while(temp->info!=ele&&temp->rptr!=NULL)
temp=temp->rptr;
if(temp->info==ele)
return temp;
}
template<class T>
void dll<T>::display()
{
node<T>*temp;
temp=head;
cout<<"\ncontents are\n";

75

while(temp!=NULL)
{
cout<<temp->info<<endl;
temp=temp->rptr;
}
}
template<class T>
void dll<T>::op()
{
int ch;
T x,ele;
node<T>*ptr;
cout<<"\nEnter 1-To prepend\n2-To append\n3-To insert before a particular
pointer\n4-To insert element after a particular pointer\n5-Delete element from the
list\n6-Display\n7-Exit";
cin>>ch;
while(1)
{
switch(ch)
{
case 1:
{
cout<<"\nEnter element to insert in the list";
cin>>x;
prepend(x);
break;
}
case 2:
{
cout<<"\nEnter element to insert in the list";
cin>>x;
append(x);
break;
}
case 3:
{
cout<<"\nEnter element to be searched";
cin>>x;
ptr=search(x);
cout<<"\nEnter element to be inserted before the desired pointer";
cin>>ele;
insbef(ptr,ele);
break;
}
case 4:
{

76

cout<<"\nEnter element to be searched";


cin>>x;
ptr=search(x);
cout<<"\nEnter element to be inserted after the desired pointer";
cin>>ele;
insaft(ptr,ele);
break;
}
case 5:
{
cout<<"\nEnter element to be deleted";
cin>>ele;
ptr=search(ele);
ext(ptr);
break;
}
case 6:
{
display();
break;
}
case7:
{
exit(0);
}
}
cout<<"\nEnter another choice";
cin>>ch;
}
}
void main()
{
int ch;
cout<<"\nEnter 1.For int\n2.For float\n3.For char";
cin>>ch;
switch(ch)
{
case 1:
{
dll<int>j;
j.op();
break;
}
case 2:
{
dll<float>j;

77

j.op();
break;
}
case 3:
{
dll<char>j;
j.op();
break;
}
}
}
Output:
Enter 1-For int
2-For float
3-For char
1
Enter 1.To prepend
2.To append
3.To insert before a particular pointer
4.To insert after a particular pointer
5.Delete element from the list
6.Display
7.Exit
1
Enter element to insert in the list 12
Enter another choice 2
Enter element to insert in the list 23
Enter another choice 3
Enter element to be searched 23
Enter element to insert before the desired pointer 36
Enter another choice 4
Enter element to be searched 12
Enter element to insert after the desired pointer 54
Enter another choice 5
Enter element to be deleted 54
Enter another choice 6
12
36
23
Enter another choice 7

78

[TOP2]

[TOP2]

//5. Write a program for polynomial arithmetic using linked list.

[TOP2]

Implementation logic:
add(list<T>p1,list<T>p2): The link list representing the two polynomials are
traverse till end of one of them is reached. While doing this they are compared on
term basis.
If the exponents are equal add the terms and store it in 3rd polynomial.
If the exponents are not equal, store the term with larger exponent in the 3 rd
polynomial.
During the traversal if the end of one of the list is reached then just append the
remaining terms of the second polynomial to the 3rd polynomial.
mul(list<T> p1,list<T> p2): Here each term of the second polynomial is multiplied
with every term of first polynomial and the new term obtained is added to the 3 rd
polynomial.
Each term of the existing resulting polynomial is scanned to find whether their exists
the term in this polynomial whose exponent is same as that of the term to be added. If
it is so then the corresponding c-efficient of the existing polynomial is updated,
otherwise the new term is simply appended to the end of existing polynomial.
Code:
#include<iostream.h>
#include<stdlib.h>
template<class T>
struct node
{
T exp,coeff;
node<T>*next;
};
template<class T>
class list
{
node<T>*head,*tail;
public:
list()
{
head=tail=NULL;
}
void append(T,T);
void add(list,list);

79

void mul(list<T>,list<T>);
void madd(T,T);
void display();
void op();
};
template<class T>
void list<T>::add(list<T>p1,list<T>p2)
{
node <T>*t1,*t2;
t1=p1.head;
t2=p2.head;
if(t1==NULL&&t2==NULL)
cout<<"\nList is empty";
else
{
while(t1!=NULL&&t2!=NULL)
{
if(t1->exp>t2->exp)
{
append(t1->coeff,t1->exp);
t1=t1->next;
}
else if(t1->exp<t2->exp)
{
append(t2->coeff,t2->exp);
t2=t2->next;
}
else if(t1->exp==t2->exp)
{
append(t1->coeff+t2->coeff,t1->exp);
t1=t1->next;
t2=t2->next;
}
}
while(t1!=NULL)
{
append(t1->coeff,t1->exp);
t1=t1->next;
}
while(t2!=NULL)
{
append(t2->coeff,t2->exp);
t2=t2->next;
}
}
}

80

template<class T>
void list<T>::append(T x,T y)
{
node<T>*new1;
new1=new node<T>;
new1->coeff=x;
new1->exp=y;
new1->next=NULL;
if(head==NULL)
head=new1;
else
tail->next=new1;
tail=new1;
}
template<class T>
void list<T>::mul(list<T> p1,list<T> p2)
{
T c,e;
node<T> *t1,*t2;
t1=p1.head;
t2=p2.head;
if(t1==NULL&&t2==NULL)
cout<<"\nList is empty";
else
{
while(t1!=NULL)
{
while(t2!=NULL)
{
c=t1->coeff*t2->coeff;
e=t1->exp+t2->exp;
t2=t2->next;
madd(c,e);
}
t2=p2.head;
t1=t1->next;
}
}
}
template<class T>
void list<T>::madd(T c,T e)
{
node<T>*temp=head;
node<T>*new1;
new1=new node<T>;
new1->coeff=c;

81

new1->exp=e;
if(head==NULL|| temp->exp<e)
{
new1->next=temp;
head=new1;
}
else
{
while(temp!=NULL)
{
if(temp->exp==e)
{
temp->coeff+=c;
return;
}
if(temp->exp>e)
{
if((temp->next==NULL)||(temp->next!=NULL&&temp->next->exp<e))
{
new1->next=temp->next;
temp->next=new1;
return;
}
}
temp=temp->next;
}
}
}
template<class T>
void list<T>::display()
{
node<T>*temp=head;
while(temp!=NULL)
{
cout<<temp->coeff<<"x^"<<temp->exp;
temp=temp->next;
if(temp!=NULL)
cout<<"+";
}
}
template<class T>
void list<T>::op()
{
list<T>s1,s2;
T x,y;
int ch;

82

cout<<"Enter\n 1-To enter first polynomial expression\n2-To enter second polynomial


expression\n3-To add\n4-To multiply\n5-To display first expression\n6-To display
second expression\n7-To exit";
cin>>ch;
while(1)
{
switch(ch)
{
case 1:
{
cout<<"\nEnter the coefficient";
cin>>x;
cout<<"\nEnter the exponent";
cin>>y;
s1.append(x,y);
break;
}
case 2:
{
cout<<"\nEnter the coefficient";
cin>>x;
cout<<"\nEnter the exponent";
cin>>y;
s2.append(x,y);
break;
}
case 3:
{
list s3;
s3.add(s1,s2);
s3.display();
break;
}
case 4:
{
list s4;
s4.mul(s1,s2);
s4.display();
break;
}
case 5:
{
s1.display();
break;
}
case 6:

83

{
s2.display();
break;
}
case 7:
{
exit(0);
}
}
cout<<"\nEnter another choice";
cin>>ch;
}
}
void main()
{
int ch;
cout<<"\nEnter 1-for int\n2-for float";
cin>>ch;
switch(ch)
{
case 1:
{
list<int>j;
j.op();
break;
}
case 2:
{
list<float>j;
j.op();
break;
}
}
}
Output:
Enter 1-for int
2-for float
1
Enter
1-To enter first polynomial expression
2-To enter second polynomial expression
3-To add
4-To multiply
5-To display first expression

84

[TOP2]

6-To display second expression


7-To exit
1
Enter the coefficient 2
Enter the exponent 2
Enter another choice 1
Enter the coefficient 3
Enter the exponent 1
Enter another choice 2
Enter the coefficient 4
Enter the exponent 1
Enter another choice 2
Enter the coefficient 5
Enter the exponent 0
Enter another choice 5
2x^2+3x^1
Enter another choice 6
4x^1+5x^0
Enter another choice 3
2x^2+7x^1+5x^0
Enter another choice 4
8x^3+22x^2+15x^1
Enter another choice 7

[TOP2]

85

//6. Write a program to convert un parenthesized infix exp to postfix exp.


Implementation logic:
[TOP2]
Initialize stack contents to the special symbol #
Scan the left most symbol in the given infix expression and denote as the current
input symbol
While the current symbol is not # DO
Remove and output all stack symbols whose precedence values are greater
than or equal to precedence of the current input symbol
Push current input symbol on to the symbol.
Scan the left most symbol in the infix expression and let it be the current input
symbol.
Remove an output all stack symbol until the top element becomes #.
Code:
#include<iostream.h>
#include<stdlib.h>
class post
{
char a[20];
int top;
public:
post()
{
top=-1;
}
void push(char c)
{
if(top==19)
cout<<"\nStack is full";
else
{
++top;
a[top]=c; }
}
char pop()
{
char t;
if(top==-1)
return -1;
86

else
{
t=a[top];
top--;
return t;
}
}
int f(char c);
int r(char c);
void convert(char[],char[]);
};
int post::f(char c)
{
switch(c)
{
case '*':
case '/':
return 2;
case '+':
case '-':
return 2;
case '#':
return 0;
default:
return 4;
}
}
int post::r(char c)
{
switch(c)
{
case '*':
case '/':
case '+':
case '-':
return -1;
default:
return 1; } }
void post::convert(char infix[],char postfix[])
{
char next,temp;
int rank=0,i=0,j=0;
push('#');
next=infix[i];
while(next!='#')
{

87

while(f(next)<=f(a[top]))
{
temp=pop();
postfix[j++]=temp;
rank=rank+r(temp);
if(rank<1)
{
cout<<"\nInvalid";
exit(0);
}
else
{
cout<<"\nValid";
}
}
push(next);
next=infix[++i];
}
while(a[top]!='#')
{
temp=pop();
postfix[j++]=temp;
}
postfix[j++]='\0';
if(rank<1)
cout<<"\nInvalid";
else
cout<<"\nValid";
}
void main()
{
char infix[20],postfix[20];
cout<<"\nEnter the infix exp";
cin>>infix;
post e;
e.convert(infix,postfix);
cout<<"\nPostfix of the given exp is\n"<<postfix;
}
Output:
Enter the infix exp a+b#
Valid
Valid
Postfix of the given exp is ab+
//7. Write a program to convert parenthesized infix to postfix expression.
Implementation logic:

[TOP2]

88

Initialize the stack content to c.


Scan the left most symbol in the given expression and denote it as the current input
symbol
While the current input symbol is not equal to \0(i.e. till end of string)
Remove and store all stack symbols whose precedence value are greater than
the precedence of the current symbol
Push current symbol on to the stack if precedence of the stack symbol is less
than that of current input symbol and if both the precedence are equal then remove
and dont store the stack symbol.
Scan the left most symbol in the given expression and let it be the current input
symbol.
Code:
#include<iostream.h>
#include<stdlib.h>
class post
{
char a[20];
int top;
public:
post()
{
top=-1;
}
void push(char c)
{
if(top==19)
cout<<"\nStack is full";
else
{
++top;
a[top]=c;
}
}
char pop()
{
char t;
if(top==-1)
return -1;
else
{
t=a[top];
top--;
return t;
}
}
int f(char c);
89

int g(char c);


int r(char c);
void convert(char[],char[]);
};
int post::f(char c)
{
switch(c)
{
case '*':
case '/':
return 3;
case '+':
case '-':
return 1;
case '(':
return 9;
case '^':
return 5;
case ')':
return 0;
default:
return 7;
}
}
int post::g(char c)
{
switch(c)
{
case '*':
case '/':
return 4;
case '+':
case '-':
return 2;
case '(':
return 0;
case '^':
return 6;
default:
return 8;
}
}
int post::r(char c)
{
switch(c)
{

90

case '*':
case '/':
case '+':
case '-':
case '(':
case ')':
case '^':
return -1;
default:
return 1;
}
}
void post::convert(char infix[],char postfix[])
{
char next,temp;
int rank=0,i=0,j=0;
push('(');
next=infix[i];
while(next!='\0')
{
while(f(next)<g(a[top]))
{
temp=pop();
postfix[j++]=temp;
rank=rank+r(temp);
if(rank<1)
{
cout<<"\nInvalid";
exit(0);
}
}
if(f(next)!=g(a[top]))
push(next);
else
pop();
next=infix[++i];
}
postfix[j++]='\0';
if(rank==1)
cout<<"\nValid";
else
{
cout<<"\nInvalid";
exit(0);
}
}

91

void main()
{
char infix[20],postfix[20];
cout<<"\nEnter the infix exp";
cin>>infix;
post e;
e.convert(infix,postfix);
cout<<"\nPostfix of the given exp is\n"<<postfix;
}
Output:
Enter the infix exp a+b)
Valid
Postfix of the given exp is ab+

92

//8. Write a program to evaluate a postfix expression.

[TOP2]

Implementation logic:
If the next component of the expression is an operand the value of the component
is pushed on the stack.
If the next component of the expression is an operator then its operands are in the
stack. The required number of operands are popped from the stack, the appropriate
operation is carried out based on the operator and the result is pushed back on to the
stack.
Code:
#include<iostream.h>
#include<stdlib.h>
#include<math.h>
#include<ctype.h>
#include<conio.h>
class postfix
{
private:
int stack[50];
int top,nn;
char *s;
public:
postfix();
void setexpr(char *str);
void push(int item);
int pop();
void calculate();
void show();
};
postfix::postfix()
{
top=-1;
}
void postfix::setexpr(char *str)
{
s=str;
}
void postfix::push(int item)

93

{
if(top==49)
cout<<endl<<"stack is full";
else
{
top++;
stack[top]=item;
}
}
int postfix::pop()
{
if(top==-1)
{
cout<<endl<<"stack is empty";
return NULL;
}
int data=stack[top];
top--;
return data;
}
void postfix::calculate()
{
int n1,n2,n3;
while(*s)
{
if(*s==' '||*s=='\t')
{
s++;
continue;
}
if(isdigit(*s))
{
nn=*s-'0';
push(nn);
}
else
{
n1=pop();
n2=pop();
switch(*s)
{
case '+':
n3=n2+n1;
break;
case '-':
n3=n2-n1;

94

break;
case '/':
n3=n2/n1;
break;
case '*':
n3=n2*n1;
break;
case '%':
n3=n2%n1;
break;
case '$':
n3=pow(n2,n1);
break;
default:
cout<<"Unknown operator";
exit(1);
}
push(n3);
}
s++;
}
}
void postfix::show()
{
nn=pop();
cout<<"Result is:"<<nn;
}
void main()
{
clrscr();
char expr[50];
cout<<"\nEnter postfix expression to be evaluated:";
cin.getline(expr,50);
postfix q;
q.setexpr(expr);
q.calculate();
q.show();
}
Output:
Enter postfix expression to be evaluated: 4 2 $ 3 * 3 8 4 / 1 1 + / +
Result is: 46

95

[TOP2]

Cycle III
1. Write a program to implement insertion sort using arrays.
2. Write a program to implement selection sort using arrays.
3. Write a program to implement Quick sort using arrays.
4. Write a program to implement Merge sort using arrays.
5. Write a program to implement tree traversal on binary tree.
6. Write a program to implement traversal on a graph.
7. Write a program to implement operations on AVL tree.
8. Write a program to implement operations on B-Tree.

96

//1. Write a program to sort elements in an array using insertion sort.


Implementation logic:

[TOP3]

insertionsort(int a[],int n): Checks if the previous value is greater than the
corresponding value if so a function to swap two values is called.
Code:
#include<iostream.h>
void insertionsort(int[],int);
void swap(int&,int&);
void insertionsort(int a[],int n)
{
for(int i=1;i<n;i++)
for(int j=i;j>0&&a[j-1]>a[j];j--)
swap(a[j],a[j-1]);
}
void swap(int &x,int &y)
{
int temp;
temp=x;
x=y;
y=temp;
}
main()
{
int n,a[50],i;
cout<<\nEnter the number of elements;
cin>>n;
cout<<\nEnter the elements;
for(i=0;i<n;i++)
cin>>a[i];
insertionsort(a,n);
cout<<\nsorted elements are\n;
for(i=0;i<n;i++)
cout<<a[i]<<endl;
return(0);
}
Output:

[TOP3]

97

Enter the number of elements 5


Enter the elements
4 6 3 87 2
sorted elements are
2 3 4 6 87
//2. Write a program to sort elements in an array using selection sort.[TOP3]
Implementation logic:
indexofmax(int[],int): Checks if the previous value is with the corresponding value
and returns the index of the greatest one.
selectionsort(int[],int): The index returned by indexofmax(int[],int) is used to find
the largest no and swap.
Code:
#include<iostream.h>
int indexofmax(int[],int);
void selectionsort(int[],int);
void swap(int&,int&);
int indexofmax(int a[],int n)
{
int index=0;
for(int i=1;i<n;i++)
if(a[index]<a[i])
index=i;
return(index);
}
void selectionsort(int a[],int n)
{
for(int size=n;size>1;size--)
{
int j=indexofmax(a,size);
swap(a[j],a[size-1]);
}
}
void swap(int &x,int &y)
{
int temp;
temp=x;
x=y;
y=temp;
}
main()
{
int n,a[50],i;
cout<<\nEnter the number of elements;

98

cin>>n;
cout<<\nEnter the elements;
for(i=0;i<n;i++)
cin>>a[i];
selectionsort(a,n);
cout<<\nsorted elements are\n;
for(i=0;i<n;i++)
cout<<a[i]<<endl;
}
Output:
Enter the number of elements 5
Enter the elements
4 6 3 87 2
sorted elements are
2 3 4 6 87

[TOP3]

99

//3. Write a program to sort elements in an array using Quick sort.[TOP3]


The core concept of quick sorting is very
A B-tree is a tree data structure that keeps data sorted and simple. Given a list, a pivot is chosen
allows searches, insertions, and deletions in logarithmic (any arbitrary element from the list). Now
amortized time. Unlike self-balancing binary search trees, it is all elements of the list, greater than the
optimized for systems that read and write large blocks of data. pivot are moved to the right. And all
It is most commonly used in databases and filesystems.
elements of the list, smaller than the pivot
A B-tree of order m (the maximum number of children for each are moved to the left. Thus we form two
node) is a tree which satisfies the following properties:
unsorted lists. One list is on the left of the
6. Every node has at most m children.
pivot, consisting of elements smaller than
7. Every node (except root and leaves) has at least m2 the pivot. Another list is to the right of the
children.
pivot, consisting of elements greater than
8. The root has at least two children if it is not a leaf node. the list. But what is important here, is that
9. All leaves appear in the same level, and carry the pivot element has found its place.
information.
Consider this list...
10. A non-leaf node with k children contains k1 keys
5 3 7 2 1 6 -The unsorted list
If we take 56b 216;5 as the pivot, the list is rearranged as follows...
3 2 1 5 7 6 - After arranging the elements around the pivot
1 2 3 5 6 7 -Sorted list (which is our target)
Observe that, even though the elements before and after 5 are not sorted, 5 has found
the place it should be after the sorting happens. That is, now we have two unsorted lists
and one element in the right place. All we have to do is do the same thing recursively for
those two unsorted lists (3, 2, 1 and 7, 6) until there are no unsorted lists and all elements
find their right place.
The program contains the following functions...
Quicksort() which quick sorts a given array
Split() which splits the array into two parts, one with smaller elements than the pivot
and another with larger elements than the pivot
Program:
#include<iostream.h>
#include<conio.h>
template <class T>
class quick
{

100

public:
T quick() {}
T swap(T &, T &);
T quick_sort(T [], T, T);
};
void main()
{
clrscr();
quick<int> myquick;
const int array_size =10;
int array[array_size]={0};
cout<<"\n array Size =10"<<endl;
cout<<" Enter the array elements:"<<endl<<endl;
for(int count=0;count<array_size;count++)
{
cout<<"\t Element["<<count<<"]=";
cin>>array[count];
}
myquick.quick_sort(array,0,array_size-1);
cout<<" Sorted array:\n";
for(count=0;count<array_size;count++)
cout<<"Element["<<count<<"]="<<array[count]<<endl;
getch();
}
template <class T>
T quick<T>::swap(T &el1,T& el2)
{
T temp = el1;
el1 = el2;
el2 = temp;
}
template <class T>
T quick<T>::quick_sort(T array[], T first, T last)
{
T cnt1, cnt2, middle, t;
if(first < last)
{
cnt1 = first;
cnt2 = last + 1;
middle = array[first];
while(cnt1<cnt2)
{

101

do {
cnt1++;
} while(array[cnt1]<middle);
do {
cnt2--;
} while(array[cnt2]>middle);
if(cnt1<cnt2)
swap(array[cnt1],array[cnt2]);
}
swap(array[first],array[cnt2]);
quick_sort(array,first,cnt2-1);
quick_sort(array,cnt2+1,last);
}
}
OUTPUT:
array Size =10
Enter the array elements:
Element[0]=4
Element[1]=1
Element[2]=6
Element[3]=2
Element[4]=8
Element[5]=5
Element[6]=7
Element[7]=9
Element[8]=3
Element[9]=10
Sorted array:
Element[0]=1
Element[1]=2
Element[2]=3
Element[3]=4
Element[4]=5
Element[5]=6
Element[6]=7
Element[7]=8
Element[8]=9
Element[9]=10

102

//4. Write a program to implement Merge Sort.

[TOP3]

MergeSort is a sorting algorithm which is more on the advanced end. It is very fast, but
unfortunately uses up a lot of memory due to the recursions. It works by recursively
splitting the array into two parts (at the midpoint if even number of elements is even,
otherwise the right half has one extra) and recursing onto each of the two halves.
Afterwards, the two halves are merged together (merging explained below). Here is a
visual example of how MergeSort recursively splits the array in half for sorting. I'm using
a diagram of a binary tree to represent the steps in our recursion process.

You may be wondering why it's [2][4][9] and not [4][9][2]. It's [2][4][9], because the
array we're merging is already sorted as it was merged the same way in all of the
recursions below the current one (below, like in the tree).
It appears that 2 is less than 3, so 2 becomes the first element in our array and is removed
from the sub-array. To remove, you can either dequeue it if you choose to implement
Queues or simply increment the 'element being compared' index variable like I did if you
use arrays.
The second comparison is made:

103

The merging continues as explained while both arrays have elements. As soon as one of
the arrays becomes empty, all the elements of the other array are blindly (without any
comparisons) appended onto our final array. Those elements are already in ascending
(sorted) order and are higher than all of the elements presently in the final array. By 'final
array', I'm referring to the array we're building while merging the two sub-arrays
together... it is the array that our MergeSort method returns.
Program for implementation of Merge Sort.
#include<iostream.h>
#include<conio.h>
const int MAX = 25;
class array
{
private:
int *arr;
int size, count;
public:
array();
array(int sz);
void add(int num);
void display();
static void sort(int *a, int sz);
void merge(array &a, array &b);
~array();
};
array::array()
{
count=size=0;
arr=NULL;
}
array::array(int sz)
{
count=0;
size=sz;
arr = new int[sz];
104

}
void array::add(int num)
{
if(count<size)
{
arr[count] = num;
count++;
}
else
{
cout<<"\n Array is full.";
}
}
void array::display()
{
for(int i=0;i<count;i++)
cout<<arr[i]<<"\t";
cout<<endl;
}
void array::merge(array &a, array &b)
{
sort(a.arr, a.size);
sort(b.arr,b.size);
size=a.count + b. count;
arr = new int[size];
int i,j,k;
for(i=j=k=0;j<a.count||k<b.count;)
{
if(a.arr[j] < b.arr[k])
arr[i++] = a.arr[j++];
else
arr[i++] = b.arr[k++];
count++;
if(j==a.count||k==b.count)
break;
}
for(;j<a.count;)
{
arr[i++] = a.arr[j++];
count++;
}
for(;k<b.count;)
{

105

arr[i++] = b.arr[k++];
count++;
}
}
void array::sort(int *a, int sz)
{
int temp;
for(int i=0;i<=sz-2;i++)
{
for(int j=i+1;j<=sz-1;j++)
{
if(a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
}
array::~array()
{
delete arr;
}
void main()
{
clrscr();
int n,m;
cout<<"\n Enter the Size of First Arry:";
cin>>m;
array a(m);
cout<<"\n Enter First Array Elements:\n";
for(int i=0;i<m;i++)
{
cin>>n;
a.add(n);
}
cout<<"\n Merge Sort \n";
cout<<"\n first Array:"<<endl;
a.display();
cout<<"\n Enter the Size of Second Arry:";
cin>>m;
array b(m);

106

cout<<"\n Enter Second Array Elements:\n";


for(i=0;i<m;i++)
{
cin>>n;
b.add(n);
}
cout<<"\n Second Array:"<<endl;
b.display();
array c;
c.merge(a,b);
cout<<"\n After Sorting:"<<endl;
c.display();
getch();
}

OUTPUT:
Enter the Size of First Arry:3
Enter First Array Elements:
4
10
2
Merge Sort
first Array:
4
10
2
Enter the Size of Second Arry:2
Enter Second Array Elements:
6
5
Second Array:
6
5
After Sorting:
2
4
5
6

10

107

//5. Write a program to implement binary tree traversals.

[TOP3]

Implementation logic:
Insert the values by using nodes with info field, left and right pointer.
preorder(node *):
1. Output the root node.
2. Traverse left subtree by calling preorder function (recursion). Pass
left subtree root to it.
3. Traverse right subtree by calling preorder function (recursion).
Pass right subtree root to it.
inorder(node *):
1. Traverse left subtree by calling inorder function (recursion). Pass
left subtree root to it.
2. Output the root node.
3. Traverse right subtree by calling inorder function (recursion). Pass
right subtree root to it.
postorder(node *):
1. Traverse left subtree by calling inorder function (recursion). Pass
left subtree root to it.
2. Traverse right subtree by calling inorder function (recursion). Pass
right subtree root to it.
3. output the root node.
Code:
#include<iostream.h>
#include<stdlib.h>
class node
{
public:
int info;
node *lptr,*rptr;
};
class btree
{

108

node *head;
public:
btree()
{
head=NULL;
}
void insert(int);
void display();
void inorder(node*);
void preorder(node *);
void postorder(node *);
};
void btree::insert(int ele)
{
node *new1=new node;
if(new1!=NULL)
{
new1->info=ele;
new1->lptr=new1->rptr=NULL;
}
if(head==NULL)
head=new1;
else
{
node *temp=head;
while(temp!=NULL)
{
if(ele>temp->info)
{
if(temp->rptr==NULL)
{
temp->rptr=new1;
return;
}
else
temp=temp->rptr;
}
else if(ele<temp->info)
{
if(temp->lptr==NULL)
{
temp->lptr=new1;
return;
}
else
temp=temp->lptr;

109

}
else
{
cout<<"duplicates not allowed";
return;
}}
}
}
void btree::display()
{
node *t=head;
if(head==NULL)
{
cout<<"tree does not exist";
return;
}
cout<<"Result of Inorder tree traversal:";
inorder(t);
cout<<"\nResult of Preorder tree traversal:";
preorder(t);
cout<<"\nResult of Postorder tree traversal:";
postorder(t);
}
void btree::inorder(node *t)
{
if(t)
{
inorder(t->lptr);
cout<<t->info<<" ";
inorder(t->rptr);
}
}
void btree::preorder(node *t)
{
if(t)
{
cout<<t->info<<" ";
preorder(t->lptr);
preorder(t->rptr);
}
}
void btree::postorder(node *t)
{
if(t)
{
postorder(t->lptr);

110

postorder(t->rptr);
cout<<t->info<<" ";
}
}
void menu()
{
cout<<"1-insert\n2-display\n3-exit\n";
}
void main()
{
btree b;
int ch,x;
menu();
cout<<"Enter choice:";
cin>>ch;
while(ch)
{
switch(ch)
{
case 1:
{
cout<<"Enter ele to be inserted:";
cin>>x;
b.insert(x);
break;
}
case 2:
{
b.display();
break;
}
case 3:
exit(0);
}
cout<<"\nEnter another choice:";
cin>>ch;
}
}
Output:
1-insert
2-display
3-exit
Enter choice:1
Enter ele to be inserted:30Enter another choice:1
Enter ele to be inserted:20Enter another choice:1

111

[TOP3]

Enter ele to be inserted:25Enter another choice:1


Enter ele to be inserted:40Enter another choice:1
Enter ele to be inserted:35Enter another choice:1
Enter ele to be inserted:36Enter another choice:1
Enter ele to be inserted:32Enter another choice:1
Enter ele to be inserted:45Enter another choice:1
Enter ele to be inserted:42Enter another choice:2
Result of Inorder tree traversal: 20 25 30 32 35 36 40 42 45
Result of preorder tree traversal: 30 20 25 40 35 32 36 45 42
Result of postorder tree traversal: 25 20 32 36 35 42 45 40 30
//6. Write a program to implement traversal on a graph. [TOP3]
Depth First Search:- Here, the starting point can be any vertex and the next vertex to be
visited is decided by the traversal you choose. If you choose the DFS, the next vertex to
be visited will be the adjacent vertex (to the starting point), which has the highest depth
value(??????...look at the graph below) and then the next adjacent vertex with the next
higher depth value and so on till all the adjacent nodes for that vertex are not visited. We
repeat this same procedure for every visited vertex of the graph. Well, I got to explain this
with the help of a graph - If V1 is the starting point of my traversal then, as you can see V2, V3 and V8 are its adjacent vertices and so in the Adjacency List of V1. Now, I am
suppose to visit these vertices, but as this is DFS, I should visit V8 first and then V2 and
V3. So, to keep track of which vertex to be visited next, we make use of a STACK, which
holds these vertex values in the DFS order. Let's see the algorithm...

Algorithm:Step-1: Set the starting point of traversal and push it inside the stack
Step-2: Pop the stack and add the popped vertex to the list of visited vertices
Step-3: Find the adjacent vertices for the most recently visited vertex( from the
Adjacency Matrix)
Step-4: Push these adjacent vertices inside the stack (in the increasing order of their
depth) if they are not visited and not there in the stack already
Step-5: Go to step-2 if the stack is not empty
BFS is an uninformed search method that aims to expand and examine all nodes of a
graph or combinations of sequence by systematically searching through every solution. In
other words, it exhaustively searches the entire graph or sequence without considering the
goal until it finds it. It does not use a heuristic.
From the standpoint of the algorithm, all child nodes obtained by expanding a node are
added to a FIFO queue. In typical implementations, nodes that have not yet been
112

examined for their neighbors are placed in some container (such as a queue or linked list)
called "open" and then once examined are placed in the container "closed".

example of a breadth-first search


Algorithm :
1. Enqueue the root node.
2. Dequeue a node and examine it.
o If the element sought is found in this node, quit the search and return a
result.
o Otherwise enqueue any leftmost successors (the direct child nodes) that
have not yet been examined.
3. If the queue is empty, every node on the graph has been examined -- quit the
search and return "not found".
4. Repeat from Step 2.
/* Program to create a graph and use Deapth First Search(DFS) and Breadth First
Search(BFS) Traversal.*/
#include<conio.h>
#include<iostream.h>
#include<stdlib.h>
void create(); // For creating a graph
void dfs(); // For Deapth First Search(DFS) Traversal.
void bfs(); // For Breadth First Search(BFS) Traversal.
struct node // Structure for elements in the graph
{
int data,status;
struct node *next;
struct link *adj;
};
struct link // Structure for adjacency list
{
struct node *next;
struct link *adj;
113

};
struct node *start,*p,*q;
struct link *l,*k;
int main()
{
int choice;
clrscr();
create();
while(1)
{
cout<<"\n-----------------------\n";
cout<<"1: DFS\n\n2: BSF\n\n3: Exit\n\n Enter your choice: ";
cin>>choice;
switch(choice)
{
case 1:
dfs();
break;
case 2:
bfs();
break;
case 3:
exit(0);
break;
default:
cout<<"Incorrect choice! Re-enter your choice after pressing enter key.";
getch();
}
}
// return 0;
}
void create() // Creating a graph
{
int dat,flag=0;
start=NULL;
cout<<" Enter the nodes in the graph(0 to end): ";
while(1)
{
cin>>dat;
if(dat==0)
break;
p=new node;
p->data=dat;

114

p->status=0;
p->next=NULL;
p->adj=NULL;
if(flag==0)
{
start=p;
q=p;
flag++;
}
else
{
q->next=p;
q=p;
}
}
p=start;
while(p!=NULL)
{
cout<<"Enter the links to "<<p->data<<" (0 to end) : ";
flag=0;
while(1)
{
cin>>dat;
if(dat==0)
break;
k=new link;
k->adj=NULL;
if(flag==0)
{
p->adj=k;
l=k;
flag++;
}
else
{
l->adj=k;
l=k;
}
q=start;
while(q!=NULL)
{
if(q->data==dat)
k->next=q;
q=q->next;
}
}

115

p=p->next;
}
cout<<"\n-------------------------\n";
return;
}
// Deapth First Search(DFS) Traversal.
void bfs()
{
int qu[20],i=1,j=0;
p=start;
while(p!=NULL)
{
p->status=0;
p=p->next;
}
p=start;
qu[0]=p->data;
p->status=1;
while(1)
{
if(qu[j]==0)
break;
p=start;
while(p!=NULL)
{
if(p->data==qu[j])
break;
p=p->next;
}
k=p->adj;
while(k!=NULL)
{
q=k->next;
if(q->status==0)
{
qu[i]=q->data;
q->status=1;
qu[i+1]=0;
i++;
}
k=k->adj;
}
j++;
}

116

j=0;
cout<<"\nBreadth First Search Results<BR>\n";
cout<<"\n---------------------------<BR>\n";
while(qu[j]!=0)
{
cout<<qu[j]<<" ";
j++;
}
getch();
return;
}
// Breadth First Search(BFS) Traversal.
void dfs()
{
int stack[25],top=1;
cout<<"\nDeapth First Search Results<BR>\n";
cout<<"\n---------------------------<BR>\n";
p=start;
while(p!=NULL)
{
p->status=0;
p=p->next;
}
p=start;
stack[0]=0;
stack[top]=p->data;
p->status=1;
while(1)
{
if(stack[top]==0)
break;
p=start;
while(p!=NULL)
{
if(p->data==stack[top])
break;
p=p->next;
}
cout<<stack[top]<<" ";
top--;
k=p->adj;
while(k!=NULL)
{
q=k->next;

117

if(q->status==0)
{
top++;
stack[top]=q->data;
q->status=1;
}
k=k->adj;
}
}
getch();
return;
}
OUTPUT:
Enter the nodes in the graph(0 to end): 1 2 3 4 5 6 7 8 0
Enter the links to 1 (0 to end) : 2 3 0
Enter the links to 2 (0 to end) : 4 5 0
Enter the links to 3 (0 to end) : 6 7 0
Enter the links to 4 (0 to end) : 8 0
Enter the links to 5 (0 to end) : 0
Enter the links to 6 (0 to end) : 0
Enter the links to 7 (0 to end) : 0
Enter the links to 8 (0 to end) : 0
----------------------------------------------1: DFS
2: BSF
3: Exit
Enter your choice: 1
Deapth First Search Results
--------------------------1 3 7 6 2 5 4 8
----------------------1: DFS
2: BSF
3: Exit

118

Enter your choice: 2


Breadth First Search Results<BR>
---------------------------<BR>
1 2 3 4 5 6 7 8
----------------------1: DFS
2: BSF
3: Exit
Enter your choice: 3

119

Вам также может понравиться