Professional Documents
Culture Documents
Lab Manual: Ee2209 - Data Structures and Algorithms Laboratory
Lab Manual: Ee2209 - Data Structures and Algorithms Laboratory
LABORATORY
LAB MANUAL
INDEX
I
LAB SYLLABUS
II
LAB PLAN
III
EE2209
32
00
LAB PLAN
SI.No
1
3
4
5
6
7
8
9
10
11
12
13
14
15
Date
b) Find the node containing the element (LOC) and its preceding node (PAR).
c)
d) Adjust the link fields so that PAR points to the next element. ie
LINK [PAR] = LINK [LOC].
e)
9
Function to insert a node at the beginning of a possibly-empty list:
function insertBeginning(List list, Node newNode)
if list.firstNode == null
list.firstNode := newNode
list.lastNode := newNode
newNode.prev := null
newNode.next := null
else
insertBefore(list, list.firstNode, newNode)
A symmetric function inserts at the end:
function insertEnd(List list, Node newNode)
if list.lastNode == null
insertBeginning(list, newNode)
else
insertAfter(list, list.lastNode, newNode)
Step 5:Deleting a node
Removing a node is easier, only requiring care with the firstNode and lastNode:
function remove(List list, Node node)
if node.prev == null
list.firstNode := node.next
else
node.prev.next := node.next
if node.next == null
list.lastNode := node.prev
else
node.next.prev := node.prev
destroy node
Viva Questions:
How would you find a cycle in a linked list? Try to do it in O(n) time. Try it using
a constant amount of memory.
10
REPRESENT A POLYNOMIAL AS LINKED LIST AND IMPLEMENT
POLYNOMIAL ADDITION
Ex. No: 2
AIM:
To represent polynomial as linked list and perform polynomial addition.
ALGORITHM:
Step 1: Creating Node.
/*Inserting an element in a sorted linked list. Let the data be sorted and put in a singly linked linear list
which is being pointed by address head .Let the new data to be entered be d.Use malloc get a node with
address pNew. Suppose we want to write a code to enter data d into the node and insert it into its
proper place in the list.*/
typedef struct node {
int data;
struct node *next;
};
struct node* pNew = (struct node*)
(malloc(sizeof(struct node)));
pNew -> data = d;
pNew ->next = NULL;
pCur = head ;
/* check if data is smaller than smallest item on the list*/
if (pNew -> data < pCur -> data )
{
pNew ->next = pCur ;
head = pNew;
}
/* now examine the remaining list */
p = pCur -> next ;
while(p!=NULL ||p->data < pNew->data )
{
pCur = pCur -> next ;
p = p -> next ;
}
pNew -> next = pCur -> next;
pCur -> next = pNew ;
A polynomial can be represented in an array or in a linked list by simply storing the coefficient and
exponent of each term. However, for any polynomial operation, such as addition or multiplication of
polynomials,
Step 2: Addition of two polynomials
Consider addition of the following polynomials
5 x12 + 2 x9 + 4x7 + 6x6 + x3
7 x8 + 2 x7 + 8x6 + 6x4 + 2x2 + 3 x + 40
The resulting polynomial is going to be
5 x12 + 2 x9 + 7 x8 + 6 x7 + 14x6 + 6x4 +x3
11
2x2 + 3 x + 40
Step 3: Result of addition is going to be stored in a third list.
Step 4: Started with the highest power in any polynomial.
Step 5: If there was no item having same exponent, simply appended the term to the new list, and continued
with the process.
Step 6: Wherever the exponents were matching, simply added the coefficients and then stored the term in
the new list.
Step 6: If one list gets exhausted earlier and the other list still contains some lower order terms, then simply
append the remaining terms to the new list.
//Pseudo code
Let phead1 , phead2 and phead3 represent the pointers of
the three lists under consideration.
Let each node contain two integers exp and coff .
Let us assume that the two linked lists already contain
relevant data about the two polynomials.
Also assume that we have got a function append to insert a
new node at the end of the given list.
p1 = phead1;
p2 = phead2;
Let us call malloc to create a new node p3 to build the
third list
p3 = phead3;
/* now traverse the lists till one list gets exhausted */
while ((p1 != NULL) || (p2 != NULL))
{
/ * if the exponent of p1 is higher than that of p2 then
the next term in final list is going to be the node of p1* /
while (p1 ->exp > p2 -> exp )
{
p3 -> exp = p1 -> exp;
p3 -> coff = p1 -> coff ;
append (p3, phead3);
/* now move to the next term in list 1*/
p1 = p1 -> next;
}
/ * if p2 exponent turns out to be higher then make p3
same as p2 and append to final list * /
while (p1 ->exp < p2 -> exp )
{
p3 -> exp = p2 -> exp;
p3 -> coff = p2 -> coff ;
append (p3, phead3);
p2 = p2 -> next;
}
/* now consider the possibility that both exponents are
same , then we must add the coefficients to get the term for
the final list */
while (p1 ->exp = p2 -> exp )
{
p3-> exp = p1-> exp;
p3->coff = p1->coff + p2-> coff ;
12
append (p3, phead3) ;
p1 = p1->next ;
p2 = p2->next ;
}
}
/* now consider the possibility that list2 gets exhausted, and there are terms remaining only in list1. So all
those terms have to be appended to end of list3. However, you do not have to do it term by term, as p1 is
already pointing to remaining terms, so simply append the pointer p1 to phead3
*/
if ( p1 != NULL)
append (p1, phead3) ;
else
append (p2, phead3);
13
Ex. No. :3
Date
AIM:
To implement tree traversals using linked list.
ALGORITHM:
Step 1: Start the process.
Step 2: Initialize and declare variables.
Step 3: Enter the choice. Inorder / Preorder / Postorder.
Step 4: If choice is Inorder then
a) Traverse the left subtree in inorder.
b) Process the root node.
c) Traverse the right subtree in inorder.
Step 5: If choice is Preorder then
a) Process the root node.
b) Traverse the left subtree in preorder.
c) Traverse the right subtree in preorder.
Step 6: If choice is postorder then
a) Traverse the left subtree in postorder.
b) Traverse the right subtree in postorder.
c) Process the root node.
Step7: Print the Inorder / Preorder / Postorder traversal.
Step 8: Stop the process.
Viva Questions:
Write a function and the node data structure to visit all of the nodes in a binary
tree.
14
How would you print out the data in a binary tree, level by level, starting at the
top?
How do you represent an n-ary tree? Write a program to print the nodes of such a
tree in breadth first order.
15
Viva questions:
Given an expression tree with no parentheses in it, write the program to give
equivalent infix expression with parentheses inserted where necessary.
16
What is stack?
17
AIM:
To implement binary search tree and to do BST operations
ALGORITHM:
find() Operation
//Purpose: find Item X in the Tree
//Inputs: data object X (object to be found), binary-search-tree node node
// Output: bst-node n containing X, if it exists; NULL otherwise.
find(X, node)f if(node = NULL)
return NULL
if(X = node:data)
return node
else if(X < node:data)
return find(X,node:leftChild)
else // X > node:data
return find(X,node:rightChild)
{
findMinimum() Operation
//Purpose: return least data object X in the Tree
//Inputs: binary-search-tree node node
// Output: bst-node n containing least data object X, if it exists; NULL otherwise.
findMin(node)f if(node = NULL) //empty tree
return NULL
if(node:leftChild = NULL)
return node
return findMin(node:leftChild)
18
}
insert() Operation
//Purpose: insert data object X into the Tree
//Inputs: data object X (to be inserted), binary-search-tree node node
//Effect: do nothing if tree already contains X;
// otherwise, update binary search tree by adding a new node containing data object X
insert(X, node)f if(node = NULL)f node = new binaryNode(X,NULL,NULL)
return
{if(X = node:data)
return
else if(X < node:data)
insert(X, node:leftChild)
else // X > node:data
insert(X, node:rightChild)
}
delete() Operation
//Purpose: delete data object X from the Tree
//Inputs: data object X (to be deleted), binary-search-tree node node
//Effect: do nothing if tree does not contain X;
// otherwise, update binary search tree by deleting the node containing data object X
delete(X, node)f if(node = NULL) //nothing to do
return
if(X < node:data)
delete(X, node:leftChild)
else if(X > node:data)
delete(X, node:rightChild)
else f // found the node to be deleted! Take action based on number of node children
if(node:leftChild = NULL and node:rightChild = NULL)f delete node
node = NULL
return
{else if(node:leftChild = NULL)f tempNode = node
19
node = node:rightChild
delete tempNode
{else if(node:rightChild = NULL)f (similar to the case when node:leftChild = NULL)
{else f //replace node:data with minimum data from right subtree
tempNode = findMin(node.rightChild)
node:data = tempNode:data
delete(node:data,node:rightChild)
}
}
}
Viva questions:
What is tree?
Write a function and the node data structure to visit all of the nodes in a
binary tree.
20
ALGORITHM:
int avl_insert(node *treep, value_t target)
{
/* insert the target into the tree, returning 1 on success or 0 if it
* already existed
*/
node tree = *treep;
node *path_top = treep;
while (tree && target != tree->value) {
direction next_step = (target > tree->value);
if (!Balanced(tree)) path_top = treep;
treep = &tree->next[next_step];
tree = *treep;
}
if (tree) return 0;
21
tree = malloc(sizeof(*tree));
tree->next[0] = tree->next[1] = NULL;
tree->longer = NEITHER;
tree->value = target;
*treep = tree;
avl_rebalance(path_top, target);
return 1;
}
void avl_rebalance_path(node path, value_t target)
{
/* Each node in path is currently balanced.
* Until we find target, mark each node as longer
* in the direction of target because we know we have
* inserted target there
*/
while (path && target != path->value) {
direction next_step = (target > path->value); path->longer
node avl_rotate_2(node *path_top, direction dir)
{
node B, C, D, E;
B = *path_top;
D = B->next[dir];
C = D->next[1-dir];
22
E = D->next[dir];
*path_top = D;
D->next[1-dir] = B;
B->next[dir] = C;
B->longer = NEITHER;
D->longer = NEITHER;
return E;
} node avl_rotate_3(node *path_top, direction dir, direction third)
{
node B, F, D, C, E;
B = *path_top;
F = B->next[dir];
D = F->next[1-dir];
/* node: C and E can be NULL */
C = D->next[1-dir];
E = D->next[dir]; *path_top = D; D->next[1-dir] = B; D->next[dir] = F; B>next[dir] = C; F->next[1-dir] = E; D->longer = NEITHER; /* assume both trees are
balanced */ B->longer = F->longer = NEITHER; if (third == NEITHER) return NULL; if
(third == dir) { /* E holds the insertion so B is unbalanced */ B->longer = 1-dir; return E;
} else { /* C holds the insertion so F is unbalanced */ F->longer = dir; return C; } } and
there you have an AVL insertion, in non-recursive style, using only constant space, but
sometimes performing more comparisons that absolutely needed.
23
HASH-INSERT (T, k)
i=0
Repeat j <-- h(k, i)
if Y[j] = NIL
then T[j] = k
Return j
use i = i +1
until i = m
error "table overflow"
For Searching:
HASH-SEARCH (T, k)
i=0
Repeat j <-- h(k, i)
if T[j] = k
then return j
i = i +1
until T[j] = NIL or i = m
Return NIL
24
7, 12, 17,
5,
5,
9, 14, 20,
9, 14,
4, 11, 16,
6, 10, 15,
//Main loop:
for i from 0 to 63
if 0 i 15 then
f := (b and c) or ((not b) and d)
g := i
else if 16 i 31
f := (d and b) or ((not d) and c)
g := (5i + 1) mod 16
else if 32 i 47
f := b xor c xor d
25
g := (3i + 5) mod 16
else if 48 i 63
f := c xor (b or (not d))
g := (7i) mod 16
temp
d :=
c :=
b :=
a :=
//Add
h0 :=
h1 :=
h2 :=
h3 :=
:= d
c
b
b + leftrotate((a + f + k[i] + w[g]) , r[i])
temp
this
h0 +
h1 +
h2 +
h3 +
Viva questions:
Define hashing.
List the hashing techniques.
How can a data be inserted in to the hash table?
What is hash table?
What are the applications of hashing techniques?
26
27
update best_solution;
end if;
if (left_child.bound > max_cost)
PQ <- left_child;
end if;
create right_child; // it skips packing the next item
if (right_child.bound > max_cost)
PQ <- right_child;
end if;
end if;
end while;
return best_solution and its cost;
end procedure;
Viva questions:
28
Ex. No. :9
AIM:To implement prim's and kruskal's algorithms.
ALGORITHM:Prims Algorithm:
E(1) is the set of the sides of the minimum genetic tree.
E(2) is the set of the remaining sides.
E(1)=0,E(2)=E
While E(1) contains less then n-1 sides and E(2)=0 do
From the sides of E(2) choose one with minimum cost-->e(ij)
E(2)=E(2)-{e(ij) }
If V(i),V(j) do not belong in the same tree then
o unite the trees of V(i) and V(j) to one tree.
end (If)
end (While)
End Of Algorithm.
Kruskals Algorithm:
1 function Kruskal(G)
2 for each vertex v in G do
3
Define an elementary cluster C(v) {v}.
4 Initialize a priority queue Q to contain all edges in G, using the weights as keys.
5 Define a tree T
//T will ultimately contain the edges of the MST
6 // n is total number of vertices
7 while T has fewer than n-1 edges do
29
8
9
10
11
12
13
14
15
16
17
Viva questions:
30
4.
5.
Assign to every node a distance value. Set it to zero for our initial node and to infinity for all other
nodes.
Mark all nodes as unvisited. Set initial node as current.
For current node, consider all its unvisited neighbours and calculate their distance (from the initial
node). For example, if current node (A) has distance of 6, and an edge connecting it with another
node (B) is 2, the distance to B through A will be 6+2=8. If this distance is less than the previously
recorded distance (infinity in the beginning, zero for the initial node), overwrite the distance.
When we are done considering all neighbours of the current node, mark it as visited. A visited
node will not be checked ever again; its distance recorded now is final and minimal.
Set the unvisited node with the smallest distance (from the initial node) as the next "current node"
and continue from step 3 .
dist[v] := infinity
previous[v] := undefined
// Initializations
// Unknown distance function from source to v
// Previous node in optimal path from source
dist[source] := 0
31
7
if dist[u] = infinity:
10
break
11
remove u from Q
12
13
14
15
dist[v] := alt
16
previous[v] := u
17
// Relax (u,v,a)
return previous[]
OUTPUT:
Viva Questions:
What is queue?
You know what a queue is .... Implement a queue class with Java. What is the cost
of enqueue and dequeue? Can you improve this? What if the queue is full (I was
using an looping array)? What kind of mechanism would you use to increase its
size?
Give a good data structure for having n queues ( n not fixed) in a finite memory
segment. You can have some data-structure separate for each queue. Try to use at
least 90% of the memory space.
32
Aim:
To implement array based circular queue and to use the same for solving producer
consumer problem
Algorithm:
33
Viva questions:
What is an array?
34
35
function heapSort(a, count) is
input: an unordered array a of length count
(first place a in max-heap order)
heapify(a, count)
end := count - 1
while end > 0 do
(swap the root(maximum value) of the heap with the last element of the heap)
swap(a[end], a[0])
(decrease the size of the heap by one so that the previous max value will
stay in its proper placement)
end := end - 1
(put the heap back in max-heap order)
siftDown(a, 0, end)
function heapify(a,count) is
(start is assigned the index in a of the last parent node)
start := (count - 2) / 2
while start 0 do
(sift down the node at index start to the proper place such that all nodes below
the start index are in heap order)
siftDown(a, start, count-1)
start := start - 1
(after sifting down the root all nodes/elements are in heap order)
function siftDown(a, start, end) is
input: end represents the limit of how far down the heap
to sift.
root := start
while root * 2 + 1 end do
(While the root has at least one child)
child := root * 2 + 1
(root*2+1 points to the left child)
(If the child has a sibling and the child's value is less than its sibling's...)
if child + 1 end and a[child] < a[child + 1] then
child := child + 1
(... then point to the right child instead)
if a[root] < a[child] then
(out of max-heap order)
swap(a[root], a[child])
root := child
(repeat to continue sifting down the child now)
else
return
Viva questions:
36
What is malloc()?
37
Viva questions:
AIM:-
38
To implement the randomized algorithm of Minimum Cut.
ALGORITHM:find_min_cut(undirected graph G) {
while there are more than 2 nodes in G do {
pick an edge (u,v) at random in G
contract the edge, while preserving multi-edges
remove all loops
}
output the remaining edges
}
Viva questions:
39