2 - Programming and Data Structures PDF
2 - Programming and Data Structures PDF
Programming
and
Data Structures
2. W
hat is the advantages of using cursor based linked list over single
linked list?
Part B (5 × 16 = 80 marks)
11. (a) I mplement circular linked list for the operations of insert, delete and
display. (16)
Or
(b) I mplement stack operations to check whether the given string is
palindrome or Not. (16)
12. (a) Explain briefly about the rotations of AVL Tree. (16)
Or
(b) E
xplain briefly about the insert operations in binary search tree.
(16)
13. (a) Explain briefly about open hashing techniques with neat example.
(16)
Or
(b) Explain about dynamic equivalence problem with an example. (16)
15. (a) A
nalyze merge sort for the following numbers using divide and
conquer strategy 25, 3, 45, 789, 87, 56, 47, 65, 30, 59, 56, 24. (16)
Or
(b) E
xplain eighth queens problem in backtracking algorithm with neat
example. (16)
(b) (i) Describe the Various schemes launched for woman and child
welfare in India.
(ii) What are the modes of transmission of HIV? And how can it be
prevented.
Solutions
Part A
1. The programmer needs to define everything related to the data type such
as how the data values are stored, the possible operations that can be
carried out with the custom data type and that it must behave like a built-
in type and not create any confusion while coding the program. Such
custom data types are called Abstract data type.
For example, if the programmer wants to define date data type which
is not available in C/C++, s/he can create it using struct or class. Only
a declaration is not enough; it is also necessary to check whether the
date is valid or invalid. This can be achieved by checking using different
conditions. The following program explains the creation of date data
type:
Example
# include <stdio.h>
# include <conio.h>
struct date
{
int dd;
int mm;
int yy;
};
void main()
{
struct date d; /* date is abstract data type */
clrscr();
printf("Enter date(dd mm yy) :");
scanf("%d %d %d",&d.dd,&d.mm, &d.yy);
printf("Date%d-%d-%d",d.dd,d.mm,d.yy);
}
OUTPUT
Enter date(dd/mm/yy): 25 10 2011
Date 25-10-2011
Explanation:
In this program, using struct keyword the date data type is declared. It
contains three-integer variables dd, mm and yy to store date, month and
year. Through scanf statement date, month and year is entered and it is
displayed using printf statement.
3.
•• The left subtree of a given node must only contain keys that are less
than the parent node's.
•• The right subtree of a given node must only contain keys that are
more than the parent node's.
•• The left and right subtrees must themselves be binary search trees,
i.e. they must have two edges that satisfy the above conditions.
•• There cannot be duplicate nodes within the tree.
4. (a + b)*(c - d) - (e / f)
* –
+ – /
a b c d e f
10.
Part B
11. (a)
CIRCULAR LINKED LIST
In circular linked list the last node points to the header node. The linear
link list can be converted to circular linked list by linking the last node to
the first node. The last node of the linear linked list holds NULL pointer,
which indicates the end of linked list but performance of linked list can
be advanced with minor adjustment in the linear linked list. Instead of
placing the NULL pointer, the address of the first node can be given
to the last node, such a list is called circular linked list (as shown in
Figure 1).
First Node
The circular linked list is more helpful as compared to singly linked list.
In the circular linked list, all the nodes of the list are accessible from the
given node. Once a node is accessed, by traversing all the nodes can be
accessed in succession.
In this type of list, the deletion operation is very easy. To delete an
element from the singly linked list, it is essential to obtain the address
of the first node of the list. For example, we want to delete the element,
say 5, which exists in the middle of the list. To remove the element five,
we need to find predecessor of five. Obviously, a particular element can
be searched using searching process in which all elements are visited
and compared. In the circular linked list, no such process is needed. The
address of predecessor can be found from the given element itself. In
addition, the operation splitting and concatenation of the list (discussed
later) are easier.
Though the circular linked list has advantages over linear linked list,
it also has some limitations. This list does not have first and last node.
While traversing the linked list, due to lack of NULL pointer, there may
be a possibility to get into an infinite loop. Thus, in the circular linked
list it is necessary to identify the end of the list. This can be done by
setting up the first and last node by convention. We detect the first node
by creating the list head, which holds the address of the first node. The
list head is also called as external pointer. We can also keep a counter,
which is incremented when nodes are created and end of the node can be
detected. Figure 2 gives an example of circular linked list with header.
Header Last Node
Element to be Deleted
11. (b)
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#define SIZE 10
typedef struct
{
int items[SIZE];
int top;
}STACK;
void push();
int pop();
void display();
int isoverflow();
int isempty();
int main()
{
STACK s;
char str[100];
int i, flag;
s.top = -1;
printf(“\nEnter a string: “);
gets(str);
for(i=0;str[i]!=’\0′; i++)
push(&s, str[i]);
flag = 1;
for(i=0;str[i]!=’\0′;i++)
{
if(str[i] != pop(&s))
{
flag = 0;
break;
}
}
if(flag == 1)
printf(“\nEntered string is palindrome\n”);
else
printf(“\nEntered string is not a palindrome\n”);
getch();
}
void push(STACK *p, int element)
{
if(isoverflow(p->top))
{
printf(“\nStack is overflow”);
}
else
{
(p->top)++;
p->items[p->top] = element;
}
}
int pop(STACK *p)
{
if(isempty(p->top))
{
printf(“\nStack is underflow”);
}
else
{
return (p->items[(p->top)--]);
}
}
void display(STACK s)
{
int i;
if(isempty(s.top))
{
printf(“\nStack is empty”);
}
else
{
for(i=s.top; i>=0; i–)
{
printf(“\n%d”, s.items[i]);
}
}
}
//Function to check stack overflow condition
int isoverflow(int top)
{
if(top == SIZE – 1)
return (1);
else
return (0);
}
//Function to check stack empty condition
int isempty(int top)
{
if(top == -1)
return (1);
else
return (0);
}
12. (a)
Characteristics of AVL Tree
The main characteristics of an AVL tree are as follows:
1. If the BF of a node is 0, it means that the height of the left sub-tree
and height of the right sub-tree is equal .
2. If the BF of a node is 1, it means that the height of the left sub-tree is
greater than the height of the right sub-tree.
3. If the BF of a node is –1, it means that the height of the left sub-tree
is lesser than the height of the right sub-tree.
A tree is said to be a complete AVL tree if all the nodes of the tree satisfy
all the three conditions discussed above. Some AVL and non-AVL trees
with their balance factors are shown in Figure 1.
1 1 0
0 0 0
2 −2
−1
1
0
0
(b) Non-AVL Trees
–2
A
Rotate Left 0 B
Rotate Left
−1 B
0 A 0 C
0 C
0
C
0 B
1 Rotate Right
B
0 A 0 C
0
A
0 C 0 C
Non-AVL Tree Non-AVL Tree AVL Tree
Figure 4 Rotate Right and Rotate Left
2 C 20 C
B
0 B 0 A
12. (b)
Binary Search Tree
A binary search tree is also called as binary sorted tree. Binary search
tree is either empty or each node N of tree satisfies the following
property:
1. The key value in the left child is not more than the value of root.
2. The key value in the right child is more than or identical to the value
of root.
3. All the sub-trees, i.e. left and right sub-trees follow the two rules
mentioned above.
Binary search tree is shown in Figure 1.
In Figure 1 number 7 is the root node of the binary tree. There are two
sub-trees to root 7. The left sub-tree is 4 and right sub-tree is 8. Here,
the value of left sub-tree is lower than root and value of right sub-tree
is higher than root node. This property can be observed at all levels in
the tree.
7
4 8
3 5 1 9
4 6
}
else
{
if(no<bt->data)
bt->left=insert(bt->left,no);
else
if(no>bt->data)
bt->right=insert(bt->right,no);
else
if(no==bt->data)
{
puts("Duplicates nodes: Program exited");
exit(0);
}
}
return(bt);
}
void search(struct tree*bt, long fn)
{
if(bt==NULL)
puts("The number does not exit");
else
if(fn==bt->data)
printf("The number %d is present in tree",fn);
else
if(fn<bt->data)
search(bt->left,fn);
else
search(bt->right, fn);
}
OUTPUT
Enter the nodes of tree in preorder: and 0 to quit
3 5 11 17 34 0
Enter the number to search:-17
The number 17 is present in tree
Enter the nodes of tree in preorder: and 0 to quit
3 5 11 17 34 0
Enter the number to search:-4
The number does not exit
Explanation:
This program contains struct tree which is used to store the binary
tree. The insert() function inserts the nodes into the binary tree. The
search() function searches the number from the tree. The fn variable
is used to store the number which the user will not find. The search
function first compares the fn with the root node. If the value of fn is
less than the root node then the function searches the number in the left
sub-tree, else it finds the number in the right sub-tree.
Insertion of an Element in Binary Search Tree
Insertion of an element in binary search tree needs to locate the parent
node. The element to be inserted in the tree may be on the left sub-tree
or right sub-tree. If the inserted number is lesser than the root node then
left sub-tree is recursively called, otherwise right sub-tree is chosen for
insertion. A program based on the above notion is described below.
Example: Write a program to insert an element into the binary
search tree.
# include <stdio.h>
# include <conio.h>
struct tree
{
long data;
struct tree *left;
struct tree *right;
};
int in;
struct tree *bt=NULL;
struct tree *insert(struct tree*bt,long no);
void inorder(struct tree *bt);
main()
{
long no;
clrscr();
puts("Enter the nodes of tree in preorder: and 0 to quit");
scanf("%ld",&no);
while(no!=0)
{
bt= insert(bt,no);
scanf("%d",&no);
}
printf("Enter the number to insert:- ");
scanf("%d",&in);
bt=insert(bt,in);
printf("The inorder of tree after insertion of an element\n");
inorder(bt);
}
struct tree*insert(struct tree*bt,long no)
{
if(bt==NULL)
{
bt=(struct tree*) malloc(sizeof(struct tree));
bt->left=bt->right=NULL;
bt->data=no;
}
else
{
if(no<bt->data)
bt->left=insert(bt->left,no);
else
if(no>bt->data)
bt->right=insert(bt->right,no);
else
if(no==bt->data)
{
puts("Duplicates nodes: Program exited");
exit(0);
}
}
return(bt);
}
void inorder(struct tree *bt)
{
if(bt!=NULL)
{
inorder(bt->left);
printf("%d ",bt->data);
inorder(bt->right);
}
}
OUTPUT
Enter the nodes of tree in preorder: and 0 to quit
7 5 9 0
Enter the number to insert:- 2
The inorder of tree after insertion of an element
2 5 7 9
Explanation:
This program invokes a function insert() which inserts the node
into the structure pointer object *bt. Firstly, the nodes which are to be
inserted are entered and then program calls insert() for insertion of
new element. The new inserted element firstly checks with the root of the
tree. If the number is lesser than the root node it is recursively checked
with the nodes, which are present on the left sub-tree, otherwise right
sub-tree. Appropriate position of parent node is found and the element
is inserted. After insertion, elements are arranged in inorder using the
inorder() and the same numbers are displayed on the screen.
{
t1=(struct rec *) malloc (sizeof(struct rec));
t1->left= t1->right=NULL;
t1->data=digit;
}
else
if(digit< t1->data)
t1->left=insert(t1->left,digit);
else
if(digit > t1->data)
t1->right=insert(t1->right, digit);
else
if(digit==t1->data)
{
printf("Duplicate node: program exited");
exit(0);
}
return(t1);
}
void inorder(struct rec *t1)
{
if(t1!=NULL)
{
inorder(t1->left);
printf("%d ",t1->data);
inorder(t1->right);
}
}
void preorder(struct rec *t1)
{
if(t1!=NULL)
{
printf("%d ",t1->data);
preorder(t1->left);
preorder(t1->right);
}
}
void postorder(struct rec *t1)
{
if(t1!=NULL)
{
postorder(t1->left);
postorder(t1->right);
printf("%d ",t1->data);
}
}
OUTPUT
Enter the t1 in pre order and 0 to quit
3 2 4 0
The preorder of the t1 is
3 2 4
The inorder of the t1 is
2 3 4
The post order of the t1 is
2 4 3
Explanation:
The program first gets the binary search tree into the structure object t1.
And the insert() is used to insert the element into the tree. The three
functions inorder(), preorder() and postorder() are used to traverse
the tree in appropriate manner.
13. (a)
Open Addressing:
It is also called closed hashing which is used to resolve collisions with
linked list. Three common
Collision resolution strategies are:
•• Linear Probing
•• Quadratic Probing
•• Double Hashing
Linear Probing:
In Linear Probing, F is a linear function of I, typically F(i) = i. The
following fig shows the result of inserting key {89, 18, 49, 58, 69} into
hash table using the same hash function and collision resolution strategy
F(i) = i.
2 69
3
4
5
6
7
8 18 18 18 18
9 89 89 89 89 89
The first collision occurs when 49 is inserted and it is put in next
available spot, spot 0. The key 58 collides with 18, 89 and then 49 and
so it is put is next available free spot, spot 1.
Disadvantage: Even if the table is empty, blocks of occupied cells start
forming. This is known as primary clustering.
Quadratic Probing:
It eliminates the primary clustering problem of linear probing. The
choice is F(i) = i2. The following fig shows the example of quadratic
probing.
When 49 collides with 89, the next cell is attempted and since it is empty
it is placed there. Next 58, collides at spot 8. Then the next cell is tried,
8 18 18 18 18
9 89 89 89 89 89
13. (b)
The Dynamic Equivalence Problem
Given an equivalence relation ~, the natural problem is to decide, for any
a and b, if a ~ b. If the relation is stored as a two-dimensional array of
booleans, then, of course, this can be done in constant time. The problem
is that the relation is usually not explicitly, but rather implicitly, defined.
As an example, suppose the equivalence relation is defined over the
five-element set {a1, a2, a3, a7, a5}. Then there are 25 pairs of elements,
each of which is either related or not. However, the information a1 ~ a2,
a3 ~ a4, a5 ~ a1, a4 ~ a2 implies that all pairs are related. We would like to
be able to infer this quickly.
The equivalence class of an element a ∈ S is the subset of S that
contains all the elements that are related to a. Notice that the equivalence
classes form a partition of S: every member of S appears in exactly one
equivalence class. To decide if a ~ b, we need only to check whether a
and b are in the same equivalence class. This provides our strategy to
solve the equivalence problem.
The input is initially a collection of N sets, each with one element. This
initial representation is that all relations (except reflexive relations) are
false. Each set has a different element, so that Si ∩ Sj = ∅; this makes
the sets disjoint,
There are two permissible operations. The first is Find, which returns
the name of the set (that is, the equivalence class) containing a given
element. The second operation adds relations. If we want to add the
relation a ~ b, then we first see if a and b are already related. This is done
by performing Finds on both a and b and checking whether they are in
the same equivalence class. If they are not, then we apply Union. This
operation merges the two equivalence classes containing a and b into
a new equivalence class. From a set point of view, the result of U is to
create a new set Sk = Si ∪ Sj, destroying the originals and preserving the
disjointness of all the sets. The algorithm to do this is frequently known
as the disjoint set Union/Find algorithm for this reason.
or Find operation over the course of the algorithm. If there are fewer
Finds, this bound is not acceptable.
One idea is to keep all the elements that are in the same equivalence
class in a linked list. This saves time when updating, because we do not
have to search through the entire array. This by itself does not reduce the
asymptotic running time, because it is still possible to perform Θ(N2)
equivalence class updates over the course of the algorithm.
If we also keep track of the size of each equivalence class, and when
performing Unions we change the name of the smaller equivalence class
to the larger, then the total time spent for N - 1 merges is O(N log N).
The reason for this is that each element can have its equivalence class
changed at most log N times, since every time its class is changed, its
new equivalence class is at least twice as large as its old. Using this
strategy, any sequence of M Finds and up to N - 1 Unions takes at most
O(M + N log N) time.
In the remainder of this chapter, we will examine a solution to the
Union/Find problem that makes Unions easy but Finds hard. Even so,
the running time for any sequence of at most M Finds and up to N - 1
Unions will be only a little more than O(M +N).
14. (a)
A second greedy strategy is continually to select the edges in order of
smallest weight and accept an edge if it does not cause a cycle. The
action of the algorithm on the graph in the preceding example is shown
in Figure 1.
14. (b)
If the graph is weighted, the problem (apparently) becomes harder, but
we can still use the ideas from the unweighted case.
dv, each phase will take O(|V|) time to find the minimum, and thus O(|V|2)
time will be spent finding the minimum over the course of the algorithm.
The time for updating dw is constant per update, and there is at most one
update per edge for a total of O(|E|). Thus, the total running time is O(|E|
+ |V|2) = O(|V|2). If the graph is dense, with |E| = Θ(|V|2), this algorithm
is not only simple but essentially optimal, since it runs in time linear in
the number of edges.
If the graph is sparse, with |E| = Θ(|V|), this algorithm is too slow. In this
case, the distances would need to be kept in a priority queue. There are
actually two ways to do this; both are similar.
Lines 2 and 5 combine to form a DeleteMin operation, since once the
unknown minimum vertex is found, it is no longer unknown and must
be removed from future consideration. The update at line 9 can be
implemented two ways.
One way treats the update as a DecreaseKey operation. The time to find
the minimum is then O(log|V|), as is the time to perform updates, which
amount to DecreaseKey operations. This gives a running time of O(|E|
log |V| + |V|log|V|) = O(|E|log |V|), an improvement over the previous
bound for sparse graphs. Since priority queues do not efficiently support
the Find operation, the location in the priority queue of each value of
di will need to be maintained and updated whenever di changes in the
priority queue. If the priority queue is implemented by a binary heap,
this will be messy. If a pairing heap (Chapter 12) is used, the code is not
too bad.
An alternate method is to insert w and the new value dw into the priority
queue every time line 9 is executed. Thus, there may be more than one
representative for each vertex in the priority queue. When the DeleteMin
operation removes the smallest vertex from the priority queue, it must be
checked to make sure that it is not already known. Thus, line 2 becomes
a loop performing DeleteMins until an unknown vertex emerges.
Although this method is superior from a software point of view, and is
certainly much easier to code, the size of the priority queue could get to
be as large as |£|. This does not affect the asymptotic time bounds, since
|E| ≤ |V|2 implies that log|E| ≤ 2 log |V|. Thus, we still get an O(|E|log|V|)
algorithm. However, the space requirement does increase, and this could
be important in some applications. Moreover, because this method
requires |E| DeleteMins instead of only |V|, it is likely to be slower in
practice.
Notice that for the typical problems, such as computer mail and
mass transit commutes, the graphs are typically very sparse because
most vertices have only a couple of edges, so it is important in many
applications to use a priority queue to solve this problem.
There are better time bounds possible using Dijkstra’s algorithm if
different data structures are used. In Chapter 11, we will see another
priority queue data structure called the Fibonacci heap. When this is
used, the running time is O(|E| + | V| log | V|). Fibonacci heaps have
good theoretical time bounds but a fair amount of overhead, so it is not
clear whether using Fibonacci heaps is actually better in practice than
Dijkstra’s algorithm with binary heaps. Needless to say, there are no
average-case results for this problem, since it is not even obvious how to
model a random graph.
15. (a)
Merge Sort
25, 3, 45, 789, 87, 56, 47, 65, 30, 59, 56, 24
Pass 1:
25 3 45 789 87 56 47 65 30 59 56 24
Sort the elements of each pair
3 25 45 789 56 87 47 65 30 59 24 56
Pass 2: Merge two pairs
3 25 45 789 56 87 47 65 30 59 24 56
Sort the elements
3 25 45 789 47 56 65 87 24 30 56 59
Pass 3: Again merge two groups
3 25 45 789 47 56 65 87 24 30 56 59
Sort the elements
3 25 45 47 56 65 87 789 24 30 56 59
Pass 4: Again merge two groups
3 25 45 47 56 65 87 789 24 30 56 59
Sort the elements
3 24 25 30 45 47 56 59 65 87 789
15. (b)
Backtracking is a technique used to solve problems with a large search
space, by systematically trying and eliminating possibilities.
Backtracking – Eight Queens Problem:
•• Continue in this fashion until either: you have solved the problem,
or you get stuck.
•• When you get stuck, remove the queens that got you there, until you
get to a row where there is another valid square to try.
4. S
how the result of inserting 2; 1; 4; 5; 9; 3; 6; 7 into an initially empty
AVL- tree.
5. What is rehashing?
7. D
oes either prim’s or Kruskal’s algorithm work if there are negative edge
weights?
Part B (5 × 16 = 80 marks)
11. (a) (i) Explain how stack is used to convert the following infix
expression into postfix form a + b* c+ (d* e + f)* g. (8)
(ii) Give the linked list implementation of stack. (8)
Or
(b) E
xplain and write the routine for insertion, deletion and finding
element in the cursor based linked list. (16)
12. (a) (i) Construct an expression tree for the expression ab + cde +**
(10)
(ii) Give a precise expression for the minimum number of nodes
in an AVL tree of height h and what is the minimum number of
nodes in an AVL tree of height 15? (6)
Or
(b) (i) Write function to perform delete min in a binary heap. (8)
(ii) Show the result of inserting 3; 1; 4; 6; 9; 2; 5; 7 into an initially
empty binary search tree. (8)
13. (a) G
iven input (4371, 1323, 6173, 4199, 4344, 9679, 1989) and a hash
function h(x) = x mod 10, show the resulting:
(i) Separate chaining hash table.
(ii) Open addressing hash table using linear probing.
(iii) Open addressing hash table using quadratic probing.
(iv) Open addressing hash table with second hash function
h2(x) = 7-(x mod 7). (16)
Or
(b) Give short note on:
(i) Dynamic equivalence problem. (8)
(ii) Smart union algorithm. (8)
14. (a) (i) Find the shortest weighted path from A to all other vertices for
the graph in given below figure.
(ii) Find the shortest unweighted path from B to all other vertices for
the graph in given below figure. (16)
Or
(b) (i) Write a routine to implement Kruskal’s algorithm. (8)
(ii) Discuss in detail about bi connectivity. (8)
15. (a) (i) Explain in detail about branch and found algorithm design
technique with an example. (10)
(ii) Write a routine for random number generator algorithm. (6)
Solutions
Part A
1. The programmer needs to define everything related to the data type such
as how the data values are stored, the possible operations that can be
carried out with the custom data type and that it must behave like a built-
in type and not create any confusion while coding the program. Such
custom data types are called Abstract data type.
For example, if the programmer wants to define date data type which
is not available in C/C++, s/he can create it using struct or class. Only
a declaration is not enough; it is also necessary to check whether the
date is valid or invalid. This can be achieved by checking using different
conditions. The following program explains the creation of date data
type:
Example
# include <stdio.h>
# include <conio.h>
struct date
{
int dd;
int mm;
int yy;
};
void main()
{
struct date d; /* date is abstract data type */
clrscr();
printf("Enter date(dd mm yy) :");
scanf("%d %d %d",&d.dd,&d.mm, &d.yy);
printf("Date%d-%d-%d",d.dd,d.mm,d.yy);
}
OUTPUT
Enter date(dd/mm/yy): 25 10 2011
Date 25-10-2011
Explanation:
In this program, using struct keyword the date data type is declared. It
contains three-integer variables dd, mm and yy to store date, month and
year. Through scanf statement date, month and year is entered and it is
displayed using printf statement.
2. Applications of Stack:
•• Balancing Symbols
•• Postfix Expressions
•• Infix to Postfix conversion
•• Function calls
Applications of Queue:
•• To give efficient running times
•• First come First serve
4.
2 6
1 3 5 9
5. If the table gets too full, the running time for the operations will start
taking too long and Inserts might fail for open addressing hashing with
quadratic resolution. This can happen if there are too many removals
intermixed with insertions. A solution, then, is to build another table that
is about twice as big (with an associated new hash function) and scan
down the entire original hash table, computing the new hash value for
each (nondeleted) element and inserting it in the new table
6.
Set Type Find (Element Type X, Disjset S)
{
if (S[X] < = 0)
return X;
else
return Find (S[X], S)
}
8. Applications of Graph:
• Find Maximum number
• Travelling sales man problem
• Finding Strong components
9.
Greedy Algorithm Dynamic Programming
• Greedy algorithm is a meth- • Dynamic Programming is a
od for solving optimization method for solving optimiza-
problems. tion problems.
• Greedy algorithms are usually • Dynamic Programming pro-
more efficient than Dynamic vides efficient solutions for
Programming solutions some problems for which a
brute force approach would be
very slow
10.
Part B
Next a ‘*’ is read. The top entry on the operator stack has lower
precedence than ‘*’, so nothing is output and ‘*’ is put on the stack.
Next, c is read and output. Thus far, we have
The next symbol is a ‘+’. Checking the stack, we find that we will pop
a ‘*’ and place it on the output; pop the other ‘+’, which is not of lower
but equal priority, on the stack; and then push the ‘+’.
The next symbol read is a ‘+’. We pop and output ‘*’ and then push ‘+’.
Then we read and output f.
Now we read a ‘)’, so the stack is emptied back to the ‘(’. We output a
‘+’.
We read a ‘*’ next; it is pushed onto the stack. Then g is read and output.
The input is now empty, so we pop and output symbols from the stack
until it is empty.
As before, this conversion requires only O(N) time and works in one pass
through the input. We can add subtraction and division to this repertoire
by assigning subtraction and addition equal priority and multiplication
and division equal priority. A subtle point is that the expression a - b - c
will be converted to ab - c- and not abc - -. Our algorithm does the
right thing, because these operators associate from left to right. This is
not necessarily the case in general, since exponentiation associates right
to left: 22 = 28 = 256, not 43 = 64. We leave as an exercise the problem of
3
linked list routines of the previous section, but we will rewrite the stack
routines from scratch for the sake of clarity.
First, we give the definitions in Figure 3.39. We implement the stack
using a header. Figure 3.40 shows that an empty stack is tested for in the
same manner as an empty list.
Figure 3.39 Type declaration for linked list implementation of the stack
adt
11. (b)
Many languages, such as basic and fortran, do not support pointers. If
linked lists are required and pointers are not available, then an alternative
implementation must be used. The method we will describe is known as
a cursor implementation.
The two important features present in a pointer implementation of linked
lists are as follows:
1. The data are stored in a collection of structures. Each structure
contains data and a pointer to the next structure.
2. A new structure can be obtained from the system’s global memory by
a call to malloc and released by a call to free.
Our cursor implementation must be able to simulate this. The logical
way to satisfy condition 1 is to have a global array of structures. For
any cell in the array, its array index can be used in place of an address.
Figure 3.28 gives the declarations for a cursor implementation of linked
lists.
The freelist represents an interesting data structure in its own right. The
cell that is removed from the freelist is the one that was most recently
placed there by virtue of free. Thus, the last cell placed on the freelist is
the first cell taken off. The data structure that also has this property is
known as a stack.
Stack Model
A stack is a list with the restriction that insertions and deletions can be
performed in only one position, namely, the end of the list, called the top.
The fundamental operations on a stack are Push, which is equivalent to an
insert, and Pop, which deletes the most recently inserted element. The most
recently inserted element can be examined prior to performing a Pop by use
of the Top routine. A Pop or Top on an empty stack is generally considered
an error in the stack adt. On the other hand, running out of space when
performing a Push is an implementation error but not an adt error.
Stacks are sometimes known as lifo (last in, first out) lists. The model
depicted in Figure 3.37 signifies only that Pushes are input operations
and Pops and Tops are output. The usual operations to make empty
stacks and test for emptiness are part of the repertoire, but essentially all
that you can do to a stack is Push and Pop.
Figure 3.38 shows an abstract stack after several operations. The general
model is that there is some element that is at the top of the stack, and it
is the only element that is visible.
Next, a ‘+‘ is read, so two pointers to trees are popped, a new tree is
formed, and a pointer to it is pushed onto the stack.
For convenience, we will have the stack grow from left to right in the
*
diagrams.
Next, c, d, and e are read, and for each a one-node tree is created and a
pointer to the corresponding tree is pushed onto the stack.
Continuing, a ‘*’ is read, so we pop two tree pointers and form a new
tree with a ‘*’ as root.
Finally, the last symbol is read, two trees are merged, and a pointer to the
final tree is left on the stack.
Base cases:
S(0) = 1, F(3) = 2. So, S(0) = F(3) - 1.
S(1) = 2, F(4) = 3. So, S(1) = F(4) - 1.
Induction hyprothesis:
Assume that the hypothesis S(h), = F(h + 3) - 1 is true for h = 1, · · · , k.
Inductive step:
Prove that it is also true for h = k + 1.
S(k + 1) = S(k ) + S(k - 1) + 1
= F(k + 3) - 1 + F(k + 2) - 1 + 1
= F(k + 4) - 1.
We replace S(k) and S(k - 1) with their equivalence according to the
hypothesis. Then, we get S(k + 1) = F(k + 4) - 1. Hypothesis is also
true for h = k + 1. Thus, it is true for all h.
(b) S(15) = F(18) - 1.
down when the heap size is even. You should think very carefully before
attempting this, and you must put in a prominent comment if you do use
this technique. Although this eliminates the need to test for the presence
of a right child, you cannot eliminate the requirement that you test when
you reach the bottom, because this would require a sentinel for every
leaf.
3 3 3
1 1 4
3 3 3
1 4 1 4 1 4
2
6 6 6
9 9
3 3
1 4 1 4
2 2
6 6
5 9 5 9
13. (a)
Separate chaining hash table.
1 4371
3 6173 1323
4 4344
0 9679
1 4371
2 1989
3 1323
4 6173
5 4344
6
7
8
9 4199
in Figure 8.10 would form. Had the size heuristic not been used, a deeper
tree would have been formed (Fig. 8.11).
Figure 9.63 Depth-first tree for previous graph, with Num and Low
Figure 9.67 Testing for articulation points in one depth-first search (test
for the root is omitted) (pseudocode)
random sequence occurs all the time. When the program seems to work,
either the system clock can be used or the user can be asked to input a
value for the seed.
It is also common to return a random real number in the open interval
(0,1) (0 and 1 are not possible values); this can be done by dividing
by M. From this, a random number in any closed interval [a, b] can
be computed by normalizing. This yields the “obvious” routine in
Figure 10.54 which, unfortunately, works on few machines.
A quick check shows that because R < Q, all the remaining terms can
be calculated without overflow (this is one of the reasons for choosing
A = 48,271). Furthermore, d(xi) = 1 only if the remaining terms evaluate
to less than zero. Thus d(xi) does not need to be explicitly computed
but can be determined by a simple test. This leads to the program in
Figure 10.55.
least as good as the one in Figure 10.55 in their standard library. Sadly,
this is not true. Many libraries have generators based on the function
xi+1 = (Axi + C) mod 2B
where B is chosen to match the number of bits in the machine’s integer,
and C is odd. These libraries also return x;, instead of a value between 0
and 1. Unfortunately, these generators always produce values of xi that
alternate between even and odd–hardly a desirable property. Indeed,
the lower k bits cycle with period 2k (at best). Many other random
number generators have much smaller cycles than the one provided in
Figure 10.55. These are not suitable for the case where long sequences
of random numbers are needed. Finally, it may seem that we can get a
better random number generator by adding a constant to the equation.
For instance, it seems that
xi+1 = (48,271xi + 1) mod(231 - 1)
would somehow be even more random. This illustrates how fragile these
generators are.
[48,271(179,424,105) + 1] mod(231 - 1) = 179,424,105 so if the seed is
179,424,105, the generator gets stuck in a cycle of period 1.
RULE 1:
If T1(N) = O(f(N)) and T2(N) - O(g(N)), then
(a) T1(N) + T2(N) = max(O(f(N)), O(g(N))),
(b) T1(N) * T2(N) = O(f(N) * g(N)),
discussed are bin packing, knapsack, graph coloring, and clique. The
list is quite extensive and includes problems from operating systems
(scheduling and security), database systems, operations research, logic,
and especially graph theory.
3. Define binary tree and give the binary tree node structure.
4. D
raw an expression tree for the expression:
(a + b * c) + ((d * e + f) * g)
5. How does the AVL tree differ from binary search tree?
Part B (5 × 16 = 80 marks)
11. (a) (i) Write an algorithm to merge two sorted linked lists into a single
sorted list (8)
(ii) Explain the operation of inserting an element at the front, middle
and at the rear in a doubly linked list. (8)
Or
(b) (i) Write and explain an algorithm to display the contents of a stack
with an example. (8)
(ii) Briefly explain the operations of queue with examples. (8)
12. (a) (i) Explain the process of finding the minimum and maximum
elements of binary search tree. (8)
(ii) Explain the process of displaying the nodes of a binary tree at a
particular level. (8)
Or
(b) (i) Write a function to insert a node into a binary search tree and
explain with an example. (8)
(ii) Explain the operations of threaded binary tree. (8)
13. (a) (i) Explain the insert and delete operations of heap with examples.
(8)
(ii) Explain how does double rotation fix the problem found in the
single rotation of AVL tree with and example. (8)
Or
(b) (i) Describe the operations of B-tree using 2-3 tree. (8)
(ii) Explain the operations which are performed in splay tree. (8)
14. (a) (i) Briefly describe linear probing and quadratic probing collision
resolution strategies. (8)
(ii) Discuss about the two permissible operations in the dynamic
equivalence problem. (8)
Or
(b) (i) Explain the algorithms which are associated with path
compression. (8)
(ii) List the advantages and disadvantages of various collision
resolution strategies. (8)
15. (a) (i) Explain the Kruskal’s algorithm to find out minimum cost
spanning tree with an example. (8)
(ii) Explain the Dijkstra’s algorithm for shortest path problem with
an example. (8)
Or
(b) (i) Explain the topological sort with an example. (8)
(ii) Given an account of Euler circuits in the applications of graph.
(8)
Solutions
Part A
1. Applications of Stack:
•• Evaluation of Postfix Expression
•• Reverse String
•• Stack Frames
•• Recursion
2. The programmer needs to define everything related to the data type such
as how the data values are stored, the possible operations that can be
carried out with the custom data type and that it must behave like a built-
in type and not create any confusion while coding the program. Such
custom data types are called Abstract data type.
For example, if the programmer wants to define date data type which
is not available in C/C++, s/he can create it using struct or class. Only
a declaration is not enough; it is also necessary to check whether the
date is valid or invalid. This can be achieved by checking using different
conditions. The following program explains the creation of date data
type:
Example
# include <stdio.h>
# include <conio.h>
struct date
{
int dd;
int mm;
int yy;
};
void main()
{
struct date d; /* date is abstract data type */
clrscr();
printf("Enter date(dd mm yy) :");
scanf("%d %d %d",&d.dd,&d.mm, &d.yy);
printf("Date%d-%d-%d",d.dd,d.mm,d.yy);
}
OUTPUT
Enter date(dd/mm/yy): 25 10 2011
Date 25-10-2011
Explanation:
In this program, using struct keyword the date data type is declared. It
contains three-integer variables dd, mm and yy to store date, month and
year. Through scanf statement date, month and year is entered and it is
displayed using printf statement.
3. A binary tree is a finite set of data elements. A tree is binary if each node
of it has a maximum of two branches. The data element is either empty
or holds a single element called root along with two disjoint trees called
left sub-tree and right sub-tree, i.e. in a binary tree the maximum degree
of any node is two.
7. Any key that hashes into the cluster will require several attempts to
resolve the collision , and then it will add to the cluster is said to be
primary clustering.
9. A graph,Gr , which show for each edge , how much more flow can be
added.This can be calculated by subtracting the current flow from the
capacity for each edge.This Is said to be residual graph.
10. In the dual graph the edges represent the activities, and the vertices
represent the commencement and termination of activities. For this
reason, the dual graph is called an event- node graph
Part B
Merging is a process in which two lists are merged to form a new list. The
new list is termed as the sorted list. Before merging, individual lists are
sorted and then merging is done. The procedure is very straightforward.
Consider two arrays containing integer elements. The elements of the
first array are added successively. The result of the addition of all the
elements of the first array is added with the successive elements of the
second array. Thus, one obtains the summation of all the elements of two
arrays. Initially, sum is assumed to 0. Successively, addition of elements
is carried out with the sum. It is then compared with the elements of the
two arrays. In case there is no match, the assumed value is incremented
till it matches the array element value (ascending order). This process is
repeated till the assumed value reaches the obtained sum. A program on
merge sort is discussed below.
Example: Write a program to create two arrays containing integer
elements. Sort and store the elements of both the arrays in the third list.
# include <stdio.h>
# include <conio.h>
# include <math.h>
void main()
{
int m,n,p,sum=0;
int a[5],b[5],c[10];
clrscr();
printf("\n Enter elements for first list : ");
for(m=0;m<5;m++)
{
scanf("%d",&a[m]);
if(a[m]==0)
m--;
sum=sum+abs(a[m]);
}
0 1 2 3 4 5 6 7 8 9
Explanation:
In the above program, three arrays a[], b[] and c[] are declared. Using
for loop, elements
in a[] and b[] are declared. The sum of all the ten elements entered in
both the arrays is taken as the variable sum. The while and nested for
loop checks the corresponding elements of both the lists:
a) If one of the corresponding elements is the same, that element is
stored in the c[] array.
b) If both the corresponding elements are same, they are stored in
successive locations in the c[].
The value of m is initially zero. The sum obtained is again subtracted
from m. This is because negative numbers have to be considered while
sorting. For example, the value of sum = 20. In real execution, the sum
may be different depending on the integers entered.
Value of m would be m = –20 (as m = m – 20 when m = 0)
Thus, in the while loop, the value of m varies from –20 to 20. All the
entered elements are covered in this range. The value of m changes from
–20 to 20, i.e. –20, –19 up to +20 in ascending order. Thus, the same
order is applied while saving element in c[].
5 New node
We know that the head node of the doubly linked list contains NULL
value. When a new node is to be inserted at the beginning, the address of
the head node is assigned to the new node. The previous pointer of the
node is assigned a NULL value. The arrow ↔ indicates that the node has
both previous and next pointer.
When a node is inserted at the end, the next pointer of the new node is
assigned a NULL value and the previous pointer of the node is assigned
the address of last node. Figure 6.33 describes the insertion at the end.
3 & & 9 & & 4
When a node is to be deleted from the beginning of the node, the head
pointer points to the second node. Because after deletion of first node,
the second node becomes the first. The symbol X indicates the link will
be destroyed. This is shown in Fig. 6.35.
Head
}
else
{
if(no<bt->data)
bt->left=insert(bt->left,no);
else
if(no>bt->data)
bt->right=insert(bt->right,no);
else
if(no==bt->data)
{
puts("Duplicates nodes: Program exited");
exit(0);
}
}
return(bt);
}
void search(struct tree*bt, long fn)
{
if(bt==NULL)
puts("The number does not exit");
else
if(fn==bt->data)
printf("The number %d is present in tree",fn);
else
if(fn<bt->data)
search(bt->left,fn);
else
search(bt->right, fn);
}
OUTPUT
Enter the nodes of tree in preorder: and 0 to quit
3 5 11 17 34 0
Enter the number to search:-17
The number 17 is present in tree
Enter the nodes of tree in preorder: and 0 to quit
3 5 11 17 34 0
Enter the number to search:-4
The number does not exit
Explanation:
This program contains struct tree which is used to store the binary
tree. The insert() function inserts the nodes into the binary tree. The
search() function searches the number from the tree. The fn variable
is used to store the number which the user will not find. The search
function first compares the fn with the root node. If the value of fn is
less than the root node then the function searches the number in the left
sub-tree, else it finds the number in the right sub-tree.
2 8
1 4
2 8
1 4
3 5
{
TmpCell = FindMin(T→Right);
T→Element = TmpCell→Element;
T→Right = Delete (T→Element, T→Right);
}
else
{
TmpCell = T;
if (T→Left = = Null)
T = T→Right;
else
if (T→Right = = Null)
T = T→Left;
Free (TmpCell);
}
return T;
}
The working of the fully threaded binary tree is illustrated in Fig. 9.54.
In this case the left child of node points to the previous node in the
sequence of inorder traversal and right child of the node points to the
successor node in the inorder traversal of the node. In the previous two
methods left and right pointers of the first and last node in the inorder
list are NULL. But in this method the left pointer of the first node points
to the header node and the right pointer of the last node points to the
header node. The header node’s right pointer points to itself, and the left
pointer points to the root node of the tree. The use of the header is to
store the starting address of the tree. In the fully threaded binary thread
each and every pointer points to the other nodes. In this tree we do not
find any NULL pointers.
In the Fig. 9.54 the first node in the inorder is M and its left pointer
points to the left pointer of the header node. Similarly, the last node
in the inorder is L and its right pointer points to the left pointer of the
header.
In memory representation of threaded binary tree, it is very important to
consider the difference between thread and normal pointer. The threaded
binary tree node is represented in Fig. 9.55.
tends to make the tree very deep). Of course this strategy does not work
if the key is only part of a larger structure. If that is the case, then we
can keep all of the structures that have the same key in an auxiliary data
structure, such as a list or another search tree.
Unfortunately, since a leaf can hold only two or three keys, this might
not always be possible. If we now try to insert 1 into the tree, we find
that the node where it belongs is already full. Placing our new key into
this node would give it a fourth element, which is not allowed. This
can be solved by making two nodes of two keys each and adjusting the
information in the parent.
This tree has an internal node with four children, but we only allow
three per node. The solution is simple. We merely split this node into
two nodes with two children. Of course, this node might be one of three
children itself, and thus splitting it would create a problem for its parent
(which would now have four children), but we can keep on splitting
nodes on the way up to the root until we either get to the root or find a
node with only two children. In our case, we can get by with splitting
only the first internal node we see, obtaining the following tree.
If we now insert an element with key 28, we create a leaf with four
children, which is split into two leaves of two children:
The next splay step at k1 is a zig-zig, so we do the zig-zig rotation with k1,
k4, and k5, obtaining the final tree.
To see the difference that splaying makes over simple rotation, consider
again the effect of inserting keys 1, 2, 3, ..., N into an initially empty
tree. This takes a total of O(N), as before, and yields the same tree as
simple rotations. Figure 4.46 shows the result of splaying at the node
with key 1. The difference is that after an access of the node with key
1, which takes N — 1 units, the access on the node with key 2 will only
take about N/2 units instead of N — 2 units; there are no nodes quite as
deep as before.
An access on the node with key 2 will bring nodes to within N/4 of the
root, and this is repeated until the depth becomes roughly log N (an
example with N = 7 is too small to see the effect well). Figures 4.47 to
4.55 show the result of accessing keys 1 through 9 in a 32-node tree that
originally contains only left children. Thus we do not get the same bad
behavior from splay trees that is prevalent in the simple rotation strategy.
(Actually, this turns out to be a very good case. A rather complicated
proof shows that for this example, the N accesses take a total of O(N)
time.)
These figures highlight the fundamental and crucial property of splay
trees. When access paths are long, thus leading to a longer-than-normal
search time, the rotations tend to be good for future operations. When
accesses are cheap, the rotations are not as good and can be bad.
The extreme case is the initial tree formed by the insertions. All the
insertions were constant-time operations leading to a bad initial tree. At
that point in time, we had a very bad tree, but we were running ahead
of schedule and had the compensation of less total running time. Then
a couple of really horrible accesses left a nearly balanced tree, but the
cost was that we had to give back some of the time that had been saved.
The main theorem, which we will prove in Chapter 11, is that we never
fall behind a pace of O(logN) per operation: We are always on schedule,
even though there are occasionally bad operations.
2 3 5 9 13 15
4 6 7 10 11 14 16
8 12
large number of “obvious” solutions that do not work. Some of these are
presented in the exercises.
The main problem is that we might visit a portion of the graph and return
to the starting point prematurely. If all the edges coming out of the start
vertex have been used up, then part of the graph is untraversed. The
easiest way to fix this is to find the first vertex on this path that has an
untraversed edge, and perform another depth-first search. This will give
another circuit, which can be spliced into the original. This is continued
until all edges have been traversed.
As an example, consider the graph in Figure 9.70. It is easily seen that
this graph has an Euler circuit. Suppose we start at vertex 5, and traverse
the circuit 5, 4, 10, 5. Then we are stuck, and most of the graph is still
untraversed. The situation is shown in Figure 9.71.
3. Draw the expression tree for ((b + c)*a) + ((d + e*f) + g).
5. What are the differences between binary search tree and AVL .ret?
Part B (5 × 16 = 80 marks)
11. (a) (i) Explain the operations of queue with C function. (8)
(ii) Explain the array implementation of stacks. (8)
Or
(b) Explain the cursor implimentation of linked list. (16)
12. (a) Explain the traversal of binary tree with examples. (16)
Or
(b) Describe the operations of binary search tree with functions. 16)
13. (a) B
riefly explain the single rotation and double rotation of AVL tree
with examples. (16)
Or
(b) Explain the binary heap operations with examples. (16)
14. (a) F
or the given input (4371, 1323, 6173, 4199, 4344, 9679, 1989) and
a hash function n(X) = X mod 10. Show the resulting:
(i) Seperate chaining hash table.
(ii) Open addressing hash table using linear probing.
(iii) Open addressing hash table using quadratic probing.
(iv) Open addressing hash table with second hash function.
h2(X) = 7 – (X mod 7). (16)
Or
(b) Explain the smart union algorithm with example. (16)
15. (a) (i) Explain the prims algorithm with example. (8)
(ii) Explain topological sort with an example. (8)
Or
(b) (i) Explain the kruskals algorithm with example. (8)
(ii) Explain the Dijikstras algorithm with an example. (8)
Solutions
Part A
4. Threaded binary tree can be traversed by any one of the three traversals,
i.e. preorder, postorder and inorder. Further, in inorder threading there
may be one-way inorder threading or two–way inorder threading. In one
way inorder threading the right child of the node would point to the
next node in the sequence of the inorder traversal. Such a threading tree
is called right in threaded binary tree. Also, the left child of the node
would point to the previous node in the sequence of inorder traversal.
This type of tree is called as left in threaded binary tree. In case both the
children of the nodes point to other nodes then such a tree is called as
fully threaded binary tree.
3. All the sub-trees, i.e. left and right sub-trees follow the two rules
mentioned above.
AVL TREE
The AVL tree is a binary search tree. It is also known as height balanced
tree. It is used to minimize the search time by keeping every node of the
tree completely balanced in terms of height. The balance factor plays an
important role in the insertion and deletion of elements in an AVL tree.
The balance factor decides whether all the nodes of a tree are completely
balanced.
9. The critical path is an algorithm which calculates the early start and
early finishing time for an individual activity in a forward pass through
the network.
10. When a directed graph replaces its direct edges with the undirected
edges, it produces a connected graph is said to be weakly connected
graph.
Part A
for(n=0;n<S;n++)
printf(" %d ",queue[n]);
}
OUTPUT
Enter a number: 3
Enter a number: 4
Enter a number: 5
Enter a number: 6
Enter a number: 7
Queue overflow
Explanation:
This a simple example of queue that contains maximum 5 elements.
All the elements are entered and stored in the queue. The queue is
implemented by declaring array[s]. The while loop and scanf() statement
read elements through the keyboard. The rear is incremented to get
successive position in the queue. The for loop displays the elements.
Deletion of Element
The following program explains insertion and deletion operations.
# include<stdio.h>
# include <conio.h>
void main()
{
int queue[7]={11,12,13,14,15,16,17};
int i,r=6,f=0,n;
clrscr();
printf("\nThe Elements of queue are as follows:-\n");
for(i=0;i<7;i++)
printf("%2d ",queue[i]);
printf("\nInitial values rear=%d front=%d",r,f);
printf("\n\nHow many elements u want to delete: ");
scanf("%d",&n);
while(f<n)
{
queue[f]=NULL;
f++;
printf("\nrear=%d front=%d",r,f);
}
printf("\n Queue elements are: ");
for(n=0;n<7;n++)
printf(" %d ",queue[n]);
}
OUTPUT
The Elements of queue are as follows:-
11 12 13 14 15 16 17
Initial values rear=6 front=0
How many elements u want to delete: 3
rear=6 front=1
rear=6 front=2
rear=6 front=3
Explanation:
This program is the second part of the first program. We have started
exactly from where we ended the last program. The output of the last
program is starting of this program. The array is initialized with entered
values and rear and front are initialized to six and zero, respectively.
Static Implementation
Static implementation can be achieved using arrays. Though, it is a
very simple method, it has few limitations. Once a size of an array is
declared, its size cannot be modified during program execution. It is
also inefficient for utilization of memory. While declaration of an array,
memory is allocated which is equal to array size. The vacant space of
stack (array) also occupies memory space. In both cases, if we store less
argument than declared, memory is wasted and if we want to store more
elements than declared, array cannot be expanded. It is suitable only
when we exactly know the number of elements to be stored.
Example: Write a program to explain working of stack using array
implementation.
# include <stdio.h>
# include <conio.h>
# include <process.h>
void main()
{
int j,stack[5]={0};
int p=0;
clrscr();
printf("Enter Elements, put zero to exit: \n");
while(1)
{
scanf("%d",&stack[p]);
if(stack[p]==0)
{
printf("\n By choice terminated: ");
exit(0);
}
p++;
if(p>4)
{
printf("Stack is full \n");
break;
}
else
printf("Stack is empty\n");
}
printf("\n Elements of stack are: ");
for(j=0;j<5;j++)
printf(" %d ",stack[j]);
}
OUTPUT
Enter Elements, put zero to exit:
4
Stack is empty
2
Stack is empty
6
Stack is empty
8
Stack is empty
3
Stack is full
Explanation:
In this program, an array stack [5] is declared. Using while loop, elements
are entered through the keyboard and placed in an array. The value of
variable p is initially zero. The variable p increases in every iteration.
The variable p acts as a top of stack. The if statement checks the value
of p . If the value of p is greater than four it means that, the stack is full
and no more elements can be added. When value of p is less than four
it means more elements can be inserted in the stack. The for loop and
printf statements display the array elements. In stack random insertion
or deletion of element is not possible (Though in array it is possible, but
here keep in mind that we are treating an array as a stack. Hence, we
have to follow the restrictions that exist in stack implementation). If we
want to delete any particular element, we have to delete every element
present before that element. Example 4.2 explains deletion of elements.
11. (b)
Refer Qn no 11. (b) May/June 2013
12. (a)
Three parameters are needed for formation of binary tree. They are
node, left and right sub-trees. Traversing is one of the most important
operations done on binary tree and frequently this operation is carried
on data structures. Traversal means passing through every node of the
tree one by one. Every node is traversed only once. Assume, root is
indicated by O, left sub-tree as L and right sub-tree as R. The following
traversal combinations are possible:
1. ORL - ROOT - RIGHT-LEFT
2. OLR - ROOT - LEFT-RIGHT
3. LOR - LEFT - ROOT- RIGHT
3. Postorder traversal.
All the above three types of traversing methods are explained below.
Inorder Traversal
The functioning of inorder traversal of a non-empty binary tree is as
follows:
1. Firstly, traverse the left sub-tree in inorder.
2. Next, visit the root node.
3. At last, traverse the right sub-tree in inorder.
In the inorder traversal firstly the left sub-tree is traversed recursively
in inorder. Then the root node is traversed. After visiting the root node,
the right sub-tree is traversed recursively in inorder. Fig. 9.22 illustrates
the binary tree with inorder traversal. The inorder traversal for the tree is
P-N-Q-M-R-O-S-V. It can be illustrated as per Fig. 9.24.
Example: Write a program for inserting the elements into the tree and
traverse the tree by the inorder.
# include <stdio.h>
# include <conio.h>
struct tree
{
long data;
struct tree *left;
struct tree *right;
};
struct tree *btree=NULL;
struct tree *insert(struct tree*btree,long digit);
void inorder(struct tree*btree);
void main()
{
long digit;
clrscr();
puts("Enter integers: and 0 to quit");
scanf("%ld",&digit);
while(digit!=0)
{
btree= insert(btree,digit);
scanf("%d",&digit);
}
puts("Inorder traversing of btree:\n");
inorder(btree);
}
struct tree*insert(struct tree*btree,long digit)
{
if(btree==NULL)
{
btree=(struct tree*) malloc(sizeof(struct tree));
btree->left=btree->right=NULL;
btree->data=digit;
}
else
{
if(digit<btree->data)
btree->left=insert(btree->left,digit);
else
{
if(digit>btree->data)
btree->right=insert(btree->right,digit);
else
if(digit==btree->data)
{
puts("Duplicates nodes: Program exited");
exit(0);
}
}
return(btree);
}
void inorder(struct tree*btree)
{
if(btree!=NULL)
{
inorder(btree->left);
printf("%4ld",btree->data);
inorder(btree->right);
}
}
OUTPUT
Enter integers: and 0 to quit
6 1 2 3 7 8 9 0
Inorder traversing of btree:
1 2 3 6 7 8 9
Explanation:
This program is used to evaluate the inorder of the given tree. The
given binary tree is stored in *btree. The elements are inserted by using
the insert(). The inorder traversing, i.e. left, root and right is done by
inorder(). Fig. 9.26 illustrates the binary tree.
The inorder of binary tree is 1, 2, 3, 6, 7, 8, and 9 as shown in Fig. 9.26.
In this traversing the root comes first and the left sub-tree and right sub-
tree at last.
}
}
OUTPUT
Enter integers: and 0 to quit
5 2 1 7 0
Preorder traversing btree:
5 2 1 7
Explanation:
The program stores the binary tree in *btree structure variable of the
structure tree. By invoking the insert() the elements are inserted. The
preorder traversing is done by using preorder(). Fig. 9.29 shows the
*btree , which is inserted in this program.
In the postorder the left sub-tree is P, Q and N and the right sub-tree is
R, V, S and O.
clrscr();
puts("Enter integers: and 0 to quit");
scanf("%ld",&digit);
while(digit!=0)
{
btree= insert(btree,digit);
scanf("%d",&digit);
}
puts("Postorder traversing btree:\n");
postorder(btree);
}
struct tree*insert(struct tree*btree,long digit)
{
if(btree==NULL)
{
btree=(struct tree*) malloc(sizeof(struct tree));
btree->left=btree->right=NULL;
btree->data=digit;
}
else
{
if(digit<btree->data)
btree->left=insert(btree->left,digit);
else
if(digit>btree->data)
btree->right=insert(btree->right,digit);
else
if(digit==btree->data)
{
12. (b)
Refer Qn no 12. (b) Nov/Dec 2013
13. (a)
Refer Qn no 12. (a) Nov/Dec 2013
13. (b)
It is easy (both conceptually and practically) to perform the two required
operations. All the work involves ensuring that the heap order property
is maintained.
Insert
To insert an element X into the heap, we create a hole in the next
available location, since otherwise the tree will not be complete. If X can
be placed in the hole without violating heap order, then we do so and are
done. Otherwise we slide the element that is in the hole’s parent node
into the hole, thus bubbling the hole up toward the root. We continue
this process until X can be placed in the hole. Figure 6.6 shows that to
insert 14, we create a hole in the next available heap location. Inserting
14 in the hole would violate the heap order property, so 31 is slid down
into the hole. This strategy is continued in Figure 6.7 until the correct
location for 14 is found.
Figure 6.6 Attempt to insert 14: creating the hole, and bubbling the
hole up
you reach the bottom, because this would require a sentinel for every
leaf.
14. (a)
Refer Qn no 13. (a) May/June 2013
14. (b)
Refer Qn no 13. (b) (ii) May/June 2013
The final table is shown in Figure 9.55. The edges in the spanning tree
can be read from the table: (v2, v1), (v3, v4), (v4, v1), (v5, v7), (v6,v7), (v7,
v4). The total cost is 16.
Figure 9.53 The table after v2 and then v3 are declared known
Figure 9.55 The table after v6 and v5 are selected (Prim's algorithm
terminates)
Third Semester
Computer Science and Engineering
DATA STRUCTURES
(Regulation 2010)
4. F
or the given binary search tree, if we remove the root and replace it with
something from the left sub-tree. What will be the value of the new root?
Justify your answer.
14
/\
2 22
/\/\
1 5 20 30
//\
4 17 40
5. How do we calculate the balance factor for each node in a AVL tree?
6. Draw the minheap for the following numbers 12, 42, 25, 63, 9.
2.4 B.E./B.Tech. Question Papers
7. C
onsider the given 4 digit number {4371, 1323, 6173, 4199, 4344, 9679,
1989} and a hash function h(X) = X(mod 10). Find the hash address of
each number using separate chaining.
10. In the graph shown, find whether the graph contains an Eulerian circuit.
Part B (5 × 16 = 80 marks)
11. (a) (i) Write the algorithm for converting Infix to Postfix Expression.
(ii) Transform the given expression to postfix (Using Stacks)
12. (a) E
xplain the three standard ways of traversing a binary tree T with a
recursive algorithm. (16)
Or
(b) W
rite an algorithm for inserting and deleting a node in a binary
search tree. (16)
13. (a) W
hat are AVL tree? Describe the different rotations defined for AVL
tree. Insert the following elements step by step in sequence into an
empty AVL tree 15, 18, 20, 21, 28, 23, 30, 26. (16)
Or
Data Structures (Nov/Dec 2011) 2.5
(b) S
how the result of inserting 15, 17, 6, 19, 11, 10, 13, 20, 8, 14, 12
one at a time, into an initially empty binary min heap. Also show the
result of performing three delete Min operations in the final binary
min heap obtained. (18)
14. (a) Write about the different types of hashing techniques in detail. (18)
Or
(b) Explain about disjoint sets and its operation in detail. (18)
15. (a) (i) Traverse the graph using depth first algorithm starting from ‘A’.
(ii) Explain the Breadth first search technique in detail with an
example.
Or
(b) (i) Write about Prim’s algorithm.
(ii) Find the minimum cost spanning tree for the given Graph G
using Kruskal algorithm
Solutions
Part A
1.
(i) Insertion and deletion are performed easily.
(ii) Find lakes constant time
3.
a b
∗
c +
9
d e
17
2 22
1 5 20 30
4 17 40
25 12
42 63
Data Structures (Nov/Dec 2011) 2.7
0
1 4371
2
3 1323 6173
4 4344
5
6
7
8
9 4199 9679 1989
2. Linear Probing:
Part B
11. (a) (i) Refer Q. No. 12(a)(ii) Nov/Dec 2009.
1.
ab
+
stack output
2.
+
abc
+ o/p
abc+
+
3.
∗
abc+d
+
4.
abc+d∗
+
5.
abc+d∗+
6.
abc+d∗+ef
+
Data Structures (Nov/Dec 2011) 2.9
7.
abc+d∗+ef+
+
8.
∗ abc+d∗+ef+
+
abc+d∗+ef+∗
+
9.
abc+d∗+ef+∗+ef
+
10.
abc+d∗+ef+∗+ef+
11 (b)
#include<stdio.h>
#include <conio.h>
#include <studlib.h>
typedef struct node
{
int data;
struct node *next;
}node;
node *create ();
node *reserve (node *head, int x);
node *cancel (node *head);
void main ()
{
int op, op1,x;
node *head = NULL;
do
{
printf(“\n1 1)creat 2)reserve 3)cancel”);
printf (“n\ Enter Your Choice”);
scanf (“%d”, & op);
}
2.10 B.E./B.Tech. Question Papers
node *create()
{
node *head, *p;
string name;
int age;
head = NULL;
prinf(“\n Enter the name”);
scanf(“%s”, & name);
printf(“\n Enter age”);
scanf(“%d”, age);
for(i = 0;i<n;i + + )
{
if(head = NULL)
name = head = (node*)malloc(size of(node));
else
{
name⋅next = (node*)malloc(size of (node));
name = name⋅next;
}
name⋅;
}
return(head);
}
node*reserve_b(node *head, int x)
{
node*name;
name = (node *)malloc(size of (node));
name⋅data = x;
name⋅next = head;
head = name;
return(head);
}
Node*cancel(node *head);
{
node *name, *q;
if(head = = NULL)
{
printf(“not registered”;
return(head);
}
name head;
Data Structures (Nov/Dec 2011) 2.11
head = head⋅next;
free(name);
return(head);
}
}
•• Preorder traversal
•• Inorder traversal
•• Postoder traversal
Preorder traversal:
•• Visit the root node first.
•• next, traverse the left subtree in preorder
•• At last, traverse the right – subtree in preorder
Preorder: ABCDEFGHI
Preorder on Preorder on
A
⇒A+ B
Preorder
on B C C
D +
D
G H G H
E F
E F
Inorder on Inorder on
A
B
Inorder
on B C C
⇒ D +A+
D
G H G H
E F
E F
recursive algorithms:
void preorder (node *T)
{
if(T! = NULL)
{
printf(“\n%d”,T→data);
preorder (T→left);
preorder (T→right);
}
}
void inorder (node *T)
{
if(T! = NULL)
{
inorder(T→left);
printf(“\n%d”,T→data);
inorder (T→right);
}
}
Search Tree
Insert(Element Type X, SearchTree T)
{
if (T = = NULL)
{
Data Structures (Nov/Dec 2011) 2.13
e.g.,: 6, 2, 8, 1, 4, 3, 5
2 8
1 4
2 8
1 4
3 5
2.14 B.E./B.Tech. Question Papers
{
Position TmpCell;
if (T = = Null)
Error (“Element not found”);
else
if (X<T→Element)
T→Left = Delete (X,T→Left);
else
if (X>T→Element)
T→Left = Delete (X,T→Left);
else
if (T→Left && T→Right)
{
TmpCell = FindMin(T→Right);
T→Element = TmpCell→Element;
T→Right = Delete (T→Element, T→Right);
}
else
{
TmpCell = T;
if (T→Left = = Null)
T = T→Right;
else
if (T→Right = = Null)
T = T→Left;
Free (TmpCell);
}
return T;
}
AVL tree is a binary search tree except that for every node in the tree,
the height of left and right subtrees can differ by atmost 1. The height of
empty tree is defined to be -1.
The different types of rotation are
Data Structures (Nov/Dec 2011) 2.15
Binary heaps:
Step 1
5 5
Step 2
5 2
2 5
2 5
Step 3
2
2 5 6
5 6
Step 4
2
5 6 2 5 6 7
Step 5
2 1
5 6 ⇒ 2 6 1 2 6 7 5
7 1 7 5
2.16 B.E./B.Tech. Question Papers
Step 6
1 1
2 6 ⇒ 2 3 1 2 3 7 5 6
7 5 7 5 6
3
Step 7
1
1 2 3 7 5 6 8
2 3
7 5 6 8
Step 8
1
1 2 3 7 5 6 8 9
2 3
7 5 6 8
Step 9
1 1
1 2 3 4 5 6 8 9 7
⇒
2 3 2 3
7 5 6 8 4 5 6 8
9 4 9 7
Initially:
Data Structures (Nov/Dec 2011) 2.17
15 18 18 18
⇒ ⇒ ⇒
18 20 15 20 15 20 21 20
21 15
21 21 21 21
⇒ ⇒ ⇒ ⇒
18 20 18 20 18 20 18 23
15 15 28 15 28 23 15 28 20
23 23 26
⇒ ⇒
18 21 18 21 23 21
15 28 20 15 28 20 30 18 28 20 30
15
13. (b) Insert 15, 17, 6, 19, 11, 10, 13, 20, 8, 14, 12 in to a binary heap
Algorithm: Insertion
void insert (int heap[], int x)
{
int n;
n = heap[0];
heap[n + 1] = x;
heap[0] = n + 1;
insert(heap, n + 1);
}
Delete Max:
Int delmax(int heap [])
{
int x,n;
N = heap[0];
X = heap[1];
Heap910 = heap[n];
Heap[0] = n-1;
Del(heap,1);
2.18 B.E./B.Tech. Question Papers
Return(x);
}
Insertion:
1. Insert
15
2. Insert
15
17
3. Insert
15
17 6
15 17
19
5.
6
15 17
19 11
11 15
17 19
Data Structures (Nov/Dec 2011) 2.19
7.
6
11 15
17 19 10
8.
6
10 11
15 17 19
7.
6
10 11
15 17 19 13
8.
6
10 11
13 15 17 19
9.
6
10 11
13 15 17 19
20 8
8 10
11 13 15 17
19 20
11.
6
8 10
11 13 15 17
19 20 14
8 10
11 13 14 15
17 19 20
13.
6
8 10
11 12 13 14
15 17 19 20
•• Linear Probing
•• Quadratic Probing
•• Double Hashing
Linear Probing:
Quadratic Probing:
When 49 collides with 89, the next cell is attempted and since it is empty
it is placed there. Next 58, collides at spot 8. Then the next cell is tried,
again collision occur. A vacant cell is formed by i2 is 22 = 4. Thus it is
placed in cell 2.
Disadvantage:
•• Performance degrades
Double Hashing:
Tree data structure is used to implement the set. The name of a set is
given by the node at the tree. The array implementation of tree represents
that P[i] is the parent of ith element
0 0 0 0
1 2 3 4
1 2 3 4
Find:
2.24 B.E./B.Tech. Question Papers
Union:
SetUnion (DisjSet S, Set Type R, Set Type R2)
{
set[R2] = R1;
}
Algorithm:
n←number of nodes
i. Initialize visited[] to fals (0
for (i = 0; i<n; i + + )
visited [i] = 0;
ii. void EFS (vertex i) [DFS/starting from i]
{
visitied [i] = 1;
for each w adjacent to i
if (!visited[w])
DFS (w);
}
V0 is marked as visited.
Data Structures (Nov/Dec 2011) 2.25
At any point in algorithm, we can see a set of vertices that have been
included in the tree and the rest of vertices have not. The algorithm the
finds at each stage, a new vertex to add to the tree by choosing the edge
(u, v) such that the cost of (u, v) is the smallest among all edges where u
is in the tree and v is not.
Void Prim(Graph G)
{
MSTtree t;
Vertex u,v;
Set of vertices v;
Set of tree vertices u;
2.26 B.E./B.Tech. Question Papers
T = null;
U = {1}
While (u≠v)
{
Let (u,v) be the lowest cost such that u is in u and v is in v-u;
T = TU{(u,v)};
u = UU{v};
}
}
Void Prim(Table T)
{
Vertex v,w;
For(i = 0; i<numvertex; i + + )
{
T[i]×known = flase
T[i] ×dist = infinity
T[i] ×path = 0;
}
For(;;)
{
Let V be the start vertex with smallest distance
T[v] ×dist = 0
T[v] ×known = True;
For each W adjacent to V
If (!T[w] ×known)
{
T[w] ×Dist = Min(T[w] ×Disst, Cvw);
T[w] ×path = v;
}
}
}
}
Adjacency Matrix
Data Structures (Nov/Dec 2011) 2.27
Vertex A B C D E F G
A 0 0 0 0 0 0 1
B 0 0 0 0 0 0 0
C 1 0 0 1 0 0 0
D 0 1 0 0 0 0 0
E 0 0 0 0 0 0 0
F 0 1 0 0 0 0 1
G 0 0 0 0 0 0 0
Indegree[A] = 1
Indegree[B] = 0
Indegree[C] = 3
Indegree[D] = 1
Indegree[E] = 0
Indegree[F] = 2
Indegree[G] = 0
Third Semester
Computer Science and Engineering
(Common to Information Technology)
DATA STRUCTURES
(Regulation 2008)
Part B (5 × 16 = 80 marks)
11. (a) (i) Derive an ADT to perform insertion and deletion in a singly
linked list. (8)
(ii) Explain cursor implementation of linked lists. Write the essential
operations. (8)
Or
(b) (i) Write an ADT to implement stack of size N using an array. The
elements in the stack are to be integers. The operations to be
supported are PUSH, POP and DISPLAY. Take into account the
exceptions of stack overflow and stack underflow. (8)
(ii) A circular queue has a size of 5 and has 3 elements 10, 20 and
40 where F = 2 and R = 4. After inserting 50 and 60, what is the
value of F and R. Trying to insert 30 at this stage what happens?
Delete 2 elements from the queue and insert 70, 80 & 90. Show
the sequence of steps with necessary diagrams with the value of
F & R. (8)
12. (a) (i) Write an ADT to construct an AVL tree. (8)
(ii) Suppose the following sequences list nodes of a binary tree T in
preorder and inorder, respectively :
Preorder : A, B, D, C, E, G, F, H, J
Inorder : D, B, A, E, G, C, H, F, J
Draw the diagram of the tree. (8)
Or
(b) (i) Write an ADT for performing insert and delete operations in a
Binary Search Tree. (8)
(ii) Describe in detail the binary heaps. Construct a min heap tree
for the following :
5, 2, 6,7, 1, 3, 8, 9, 4 (8)
13. (a) (i) Formulate an ADT to implement separate chaining hashing
scheme. (8)
(ii) Show the result of inserting the keys 2, 3, 5, 7, 11, 13, 15, 6,
4 into an initially empty extendible hashing data structure with
M = 3. (8)
2.30 B.E./B.Tech. Question Papers
Or
(b) (i) Formulate an ADT to perform for the Union and find operations
of disjoint sets. (8)
(ii) Describe about Union-by-rank and Find with path compression
with code. (8)
1 4. (a) (i) Write routines to find shortest path using Dijkstra’s algorithm.
(8)
(ii) Find all articulation points in the below graph. Show the depth
first spanning tree and the values of DFN and Low for each
vertex. (8)
Or
(b) (i) Write the pseudo code to find a minimum spanning tree using
Kruskal’s algorithm. (8)
(ii) Find the topological ordering of the below graph. (8)
15. (a) (i) Discuss the running time of Divide-and-Conquer merge sort
algorithm. (8)
(ii) Explain the concept of greedy algorithm with Huffman codes
example. (8)
Or
(b) Explain the Dynamic Programming with an example. (16)
Solutions
Part A
1. ADT is a set of operations. Abstract data types are mathematical
abstractions objects such as lists, sets and graphs along with their
operations are viewed as abstract data types.
2. Array:
Advantage:
Disadvantage:
Linkedlist:
Consist of series of nodes. Each node contains the element and a pointer
to its successor node.
Advantage:
Disadvantage:
•• More memory space is required.
3. Depth of tree is the length of the unique path from root to the node n.
Height of tree is the length of largest path from node n to leaf.
4.
i) Huffman coding.
ii) Scheduling problem.
iii) Approximate Bin Packing.
2.32 B.E./B.Tech. Question Papers
5.
•• A hash function has to distribute hash indexes over the range of
array.
•• When an element is inserted, it hashes to the same value as an
already inserted element, then the collision occurs. So hash should
effectively handle collision.
8.
•• adjacency matrix representation i.e., to represent a graph by using a
two-dimensional array.
•• adjacency list representation i.e., for each vertex, we keep a list of
all adjacent vertices.
Part B
11. (a) (i) The insertion routine for a singly linked list is as follows:
TmpCell→Next = P→Next;
P→Next = TmpCell;
}
If the linked lists are required and pointers are not available, then
cursor implementation to linked lists is used. The declaration for cursor
implementation of linked list is as follows:
Position Next;
};
struct Node CursorSpace [SpaceSize];
struct StackRecord;
typedef Struct StackRecord *Stack;
int IsEmpty (Stack S);
int IsFull (Stack S);
stack CreateStack (int MaxElements);
void DisposeStack (Stack S);
void MakeEmpty (Stack S);
void Push (ElementType X, Stack S);
ElementType Top(Stack S);
void Pop(Stack S);
ElementType TopAndPop(Stack S);
Struct StackRecord
{int Capacity;
Int Topofstack;
ElementType *Array;
};
S→TopofStack − −;
}
ElementType Top(Stack S)
{
if (!IsEmpty(s))
return s→Array[s→TopofStack];
Error(“Empty stack”);
return 0;
}
20 10
Q[2]
Q[3]
F
Step1→Insert 50
To insert 50
R = [R + 1]%S
= 5%5 = 0
Q[0] = 50
R
Q[0]
50
Q[4] Q[1]
40
20 Q[2]
10
Q[3]
F
Step2→Insert 60
To insert 60;
R = [R + 1]%S = 0 + 1%5 = 1
2.36 B.E./B.Tech. Question Papers
Therefore Q[1] = 60
Now F = 2, R = 1
Q[0]
Q[4]
40 50
Q[1]
20 60 R
Q[3] 10
Q[2]
F
R = [R + 1]%S = 1 + 1%5 = 2
i.e., R = F
50 Q[1]
60 R
Q[4] 40
20
Q[2]
F
Q[3]
X = Q[3] i.e., 20
Now, F = F + 1%S
= 3 + 1%S
= 4%5
F = 4
Data Structures (Nov/Dec 2010) 2.37
Step 6 → Insert 70
R = (R + 1)%S
= 1 + 1%5
= 2%5
R=2
So 70 is inserted in Q[2]
Step 7→ Insert 80
R = R + 1%S
= 2 + 1%5 = 3%5
R=3
So 80 in inserted in Q[3]
Step 8→ Insert 90
R = R + 1%S
= 4%5
R=4
Now F = R
AVL tree is a binary search tree with a balance condition i.e., the height
of left and right subtrees can differ by atmost L
T→Element = X;
T→Height = 0;
T→Left = T→Right = Null;
}
}
else if (X<T→Element)
{
T→Left = Insert(X, T→Left);
if (Height (T→Left)−Height (T→Right) = = 2)
if (x<T→Left→Element)
T = SingleRotateWithLeft(T);
else
T = DoubleRotateWithLeft(T);
}
else if (X>T→Element)
{
T→Right = Insert (X, T→Right);
if (Height (T→Right)−Height(T→Left) = = 2)
if (X>T→Right→Element)
T = SingleRotateWithRight(T);
else
T = DoubleRotateWithRight(T);
}
T→Height = Max(Height(T→Left), Height (T→Right)) + 1;
return T;
}
Preorder: A,B,C,D,E,F,G,H,J
Inorder: D,B,A,E,G,C,H,F,J
B C
D
E F
G H I
Data Structures (Nov/Dec 2010) 2.39
Search Tree
Insert(Element Type X, SearchTree T)
{
if (T = = NULL)
{
T = malloc (size of (struct TreeNode));
if (T = = NULL)
FatalError (“Out of Spae”);
else
{
T → Element = X;
T → Left = T → Right = NULL;
}
}
else
if (X < T → Element)
T → Left = Insert (X, T → Left);
else
if (X > T → Element)
T → Right = Insert (X, T → Right);
Return T;
}
e.g.,: 6, 2, 8, 1, 4, 3, 5
2 8
1 4
2 8
1 4
3 5
{
Position TmpCell;
if (T = = Null)
Error (“Element not found”);
else
if (X<T→Element)
T→Left = Delete (X,T→Left);
else
if (X>T→Element)
T→Left = Delete (X,T→Left);
else
if (T→Left && T→Right)
{
TmpCell = FindMin(T→Right);
T→Element = TmpCell→Element;
T→Right = Delete (T→Element, T→Right);
}
else
{
TmpCell = T;
if (T→Left = = Null)
T = T→Right;
else
if (T→Right = = Null)
T = T→Left;
Free (TmpCell);
}
return T;
}
Data Structures (Nov/Dec 2010) 2.41
Step 1
5 5
Step 2
5 2
2 5
2 5
Step 3
2
2 5 6
5 6
Step 4
2
5 6 2 5 6 7
Step 5
2 1
5 6 ⇒ 2 6 1 2 6 7 5
7 1 7 5
2.42 B.E./B.Tech. Question Papers
Step 6
1 1
2 6 ⇒ 2 3 1 2 3 7 5 6
7 5 7 5 6
3
Step 7
1
1 2 3 7 5 6 8
2 3
7 5 6 8
Step 8
1
1 2 3 7 5 6 8 9
2 3
7 5 6 8
Step 9
1 1
1 2 3 4 5 6 8 9 7
⇒
2 3 2 3
7 5 6 8 4 5 6 8
9 4 9 7
int i;
if (TableSize < MinTableSize)
{
Error (“Table size small”)
return Null;
}
H = malloc(size of (struct HashTbl));
if (H = = Null)
Error (“Out of Space”);
H→TableSize = NextPrime (TableSize);
H→TheLists = malloc(sizeof(List)*H→TableSize);
if (H→TheLists = = Null)
Error (“Out of space”);
for (i = 0; i<H→TableSize; i + + )
{
H→TheLists[i] = malloc(size of (struct List Node));
if (H→TheLists[i] = = Null)
Error (“Out of space”);
else
H→TheLists[i]→Next = Null;
}
return H;
}
00 01 10 11
(2)
0010
2 To insert 3 (0011)
00 01 10 11
(2)
0010
0011
3 To insert 5 (0101)
2.44 B.E./B.Tech. Question Papers
00 01 10 11
0010 0101
0011
4 To insert 7 (0111)
00 01 10 11
0010 0101
0011 0111
Used to track of height, instead of size of each tree and perform unions
by making the shallow tree a subtree of deeper tree.
Data Structures (Nov/Dec 2010) 2.45
PathCompression:
14. (a) (i) Routine to find shortest path using Dijkstra algorithm
Dijkstra’s algorithms:
Depth first tree for the given graph with Num and Low are:
A, 1/1
B, 2/1
D, 4/1 C, 3/1
G, 7/1
E, 5/4
F, 6/4
Disjset S;
Priority Queue H;
Vertex U, V;
SetType Uset, Vset;
Edge E;
Intitialize (S);
Read Graph Into Heap Array (G, H);
Build Heap (H);
Edges Accepted = 0;
While (Edges Accepted < Numvertex - 1)
{
E = Delete Min(H);
Uset = Find (U, S);
Vset = Find (V, S);
if (Uset! = Vset)
{
Edges Accepted + + ;
SetUnion (S, Uset, Vset)
}
}
}
V1 V2 V1 V2 V1 V2
1 1
V3 V4 V5 V3 V4 V5 V3 V4 V5
1
V6 V7 V6 V7 V6 V7
2 2 2
V1 V2 V1 V2 V1 V2
1 1 1
V3 V4 V5 V3 V4 V5 V3 V4 V5
2 2 4
V6 V7 V6 V7 V6 V7
1 1 1
2
V1 V2
1
V3 V4 V5
2
4 6
V6 V7
1
Adjacency Matrix
Vertex A B C D E F G
A 0 0 0 0 0 0 1
B 0 0 0 0 0 0 0
C 1 0 0 1 0 0 0
D 0 1 0 0 0 0 0
E 0 0 0 0 0 0 0
F 0 1 0 0 0 0 1
G 0 0 0 0 0 0 0
Indegree[A] = 1
Indegree[B] = 0
Indegree[C] = 3
Data Structures (Nov/Dec 2010) 2.49
Indegree[D] = 1
Indegree[E] = 0
Indegree[F] = 2
Indegree[G] = 0
i.e., T(1) = 1
T(N) = 2T(N/2) + N
T(N) T(N/2)
i.e.,= +1
N N/2
This equation is valid for any N that is power of 2
2.50 B.E./B.Tech. Question Papers
T(N/2) T(N/4)
i.e., = +1
N/2 N/4
and
T(N/4) T(N/8)
= +1
N/4 N/8
T(2) T(1)
= +1
2 1
Now addup all the equations and the final result’s
T(N) T(1)
= + log N
N 1
Multiplying through N
T(N) = N log N + N
= 0(N log N)
Therefore Mergesort’s running time is = 0(N log N)
Scheduling problem:
j1 j2 j3 j4
0 15 23 26 36
Data Structures (Nov/Dec 2010) 2.51
j3 j2 j4 j1
0 3 11 21 36
We can show that it will yield a optimal schedule. Let the jobs in the
schedule be ji1, ji2, …, jiN. The first job finishes in time ti1. The second
job finishes after ti1 + ti2 and third job finishes after ti1 + ti2 + ti3.
C = ∑ ( N − K + 1) tik
N
(1)
k =1
eqn (2) shows the first sum is independent of job ordering and second
sum affects the total cost. These result indicates that operating system
scheduler generally gives precedence to shorter jobs.
Huffman codes:
a 000 10 30
e 001 15 45
i 010 12 36
s 011 3 9
t 100 4 12
space 101 13 39
newline 110 1 3
174
2.52 B.E./B.Tech. Question Papers
a e i s t sp nl
The tree has data only in the leaves. This tree is encoded as 011. the
main question arise is now the tree is constructed. The algorithm to do
as Huffman code
T1 4
10 15 12 4 13
a e i t sp s nl
T5 T4
T3
e i sp
T2
a
T1
t
s nl
Data Structures (Nov/Dec 2010) 2.53
* (A((BC)D))
* (A(B(CD)))
* ((AB)(CD))
* (((AB)C)D)
* ((A(BC))D)
The calculations show that the best ordering uses roughly one-ninth the
number of multiplications as the worst ordering. We define T(N) to be
the number. Then T(1) = T(2) = 1, T(3) = 2 and T(4) = 5
N−1
i.e., T(N) = ∑ T(i) T(N − i)
i=1
for(k = 1; k<N; k + + )
for (Left = 1; Left < = N − k; Left + + )
{
Right = Left + k;
M[Left][Right] = Infinity;
for(i = Left; i<Right; i + + )
{
ThisM = M[Left][i] + M[i + 1][Right] + C[Left − 1]
* C[i]*C[Right]
if(ThisM < M[Left][Right])
{
M[Left][Right] = ThisM;
LastChange[Left][Right] = i;
}
}
}
}
B.E./B.Tech. Degree Examination, NOV/DEC 2009
Third Semester
Computer Science and Engineering
(Common to Information Technology)
DATA STRUCTURES
(Regulation 2008)
Part B (5 × 16 = 80 marks)
11. (a) (i) Write the insertion and deletion procedures for cursor based
linked lists. (8)
2.56 B.E./B.Tech. Question Papers
(ii) Write the algorithm for the deletion and reverse operations on
doubly linked list. (8)
Or
11. (b) (i) Write an algorithm for Push and Pop operations on Stack using
Linked List. (8)
(ii) Explain the addition and deletion operations performed on a
circular queue with necessary algorithms. (8)
12. (a) (i) Write the algorithm for pre-order and post-order traversals of a
binary tree. (8)
(ii) Explain the algorithm to convert a postfix expression into an
expression tree with an example. (8)
Or
12. (b) (i) Write an algorithm to insert an item into a binary search tree and
trace the algorithm with the items 6, 2, 8, 1, 4, 3, 5. (8)
(ii) Describe the algorithms used to perform single and double
rotation on AVL tree. (8)
13. (a) D
iscuss the common collision resolution strategies used in closed
hashing system. (16)
Or
1 3. (b) (i) What is union-by-height? Write the algorithm to implement it.
(8)
(ii) Explain the path compression with an example. (8)
14. (a) (i) What is topological sort? Write an algorithm to perform
topological sort. (8)
(ii) Write the Dijkstra’s algorithm to find the shortest path. (8)
Or
14. (b) W
rite the Kruskal’s algorithm and construct a minimum spanning
tree for the following weighted graph. (16)
Data Structures (Nov/Dec 2009) 2.57
2
V1 V2
4 1 3 10
2 7
V3 V4 V5
5 8 4
6
1
V6 V7
15. (a) (i) Formulate an algorithm to multiply n-digit integers using divide
and conquer approach. (8)
(ii) Briefly discuss the applications of greedy algorithm. (8)
Or
(b) F
ind the optimal tour in the following traveling salesperson problem
using dynamic programming: (16)
5 10
1 2
6 8
8 13
10 15
20 9
4 3
12 9
Solutions
Part A
1. ADT is a set of operations. Abstract data types are mathematical
abstractions objects such as lists, sets and graphs along with their
operations are viewed as abstract data types.
2. A + B * (C - D)/(P - R)
Post fix form: ABCD -*PR -/ +
Prefix form: + A/*B - CD - PR
3. A binary tree is a tree in which no node can have more than two children
E.g.,:
A
B C
D E
Eg.:
+
a b
7. Indegree: In a directed graph, for any node v, the number of edges which
have v as their terminal node is called indegree of node v.
Data Structures (Nov/Dec 2009) 2.59
Out degree: In a directed graph, for any node v, the number of edges
which have v as their initial node is called out degree of node v.
9.
Back Tracking Branch and Bound
i) State space tree is constructed State space tree is constructed
using depth first search using best-first search
ii) No bounds are associated Bounds are associated with each
with the nodes in state-space and every node in state-space
tree. tree.
10.
•• Node cover
•• Planar Node cover
•• Undirected Hamiltonian cycle
•• Planar Undirected Hamiltonian cycle
•• Minimum edge deletion bipartite subgraph
•• Minimum node deletion bipartite subgraph
Part B
11. (a) (i) Insertion procedures for cursor based linked list
11. (a) (ii) Algorithm for the deleting an element from the doubly
linked list
[This Function delete an element from the doubly list and returns the
address of the first element TEMPHEAD is pointer which points the
first element of the list and KEY specify info of the node which is to be
deleted]
6. [Finished]
Return (TEMPHEAD)
Variables
Step 2 [else]
[Increment tos by 1]
tos ← tos + 1
Step 4 [Stop]
pop operation:
2.62 B.E./B.Tech. Question Papers
The pop operation removes the top most item to understand after
removed of top most information new value of the pointer top becomes
the previous value of top that is top = top - 1 and free position is
allocated as free space.
Algorithm:
Step 2 [Else]
[Decrement tos by 1]
tos ← tos - 1
return.
Step 3 [Stop]
11. (b) (ii) Algorithm for addition and deletion operation on a circular
queue.
procedure ADDQ {item, Q, n, front, rear)
rear(rear + 1)mod n
if front = rear than call QUEUE-FULL
Q(rear) item
end ADDQ
procedure DELETE Q{item, Q, n, front, rear)
if front = rear then call QUEUE-EMPTY
front (front + 1) nod n
item Q(front)
end DELETE Q
12. (a) (i) Algorithm for pre-order and post-order traversals of a binary
tree.
Preorder traversal
Struct node * ptr
{
if (root = = NULL)
{
Data Structures (Nov/Dec 2009) 2.63
Single Rotation
Static Position
SingleRotateWithLeft (Position K2)
{
Position K1;
K1 = K2 → Left;
K2 → Left = K1 → Right;
K1 → Right = K2;
K2 → Height = Max(Height(K2 → Left), Height (K2 → Right)) + 1;
K1 → Height = Max(Height(K1 → Left), K2 → Height) + 1;
Return K1;
}
Double Rotation
Static Position
Double Rotate With Left (Position K3)
{
K3 → Left = Single Rotate With Right(K3 → Left);
Return single Rotate With Left(K3);
}
In Union by height will keep track of height, instead of size of each tree
and perform Unions by making the shallow tree a subtree of deeper tree.
Algorithm:
Void setUnion(Disj Set S, Set Type Root1, Set Type Root2)
{
if (S[Root2] < S[Root1])
S[Root1] = Root2;
else
{
If (S[Root1] = = S[Root2])
S[Root1] --;
Data Structures (Nov/Dec 2009) 2.65
S[Root2] = Root1;
}
}
(ii) Union – by Size
The height of resultant tree representing S1US2, the union of two sets S1
and S2 can be reduced by making a smaller tree a subtree of larger tree.
Example:
The following fig shows the effect of path Compression after Find(15)
2 3 5 9 13 15
4 6 7 10 11 14 16
8 12
{
If(S[X] < = 0)
Return X;
Else
Return S[X] = Find (S[X], S);
}
Algorithm:
void Topsort (Graph G);
{
Queue Q;
int Counter = 0;
Vertex v, w;
Q = GreateQueue(NumVertex);
MakeEmpty(Q);
for each vertex V
if (Indegree[V] = = 0)
Enqueue(V, Q);
while(!IsEmpty(Q))
{
V = Dequeue(Q);
TopNum[V] = + + Counter;
for each W adjacent to V
if (-- Indegree[W] = = 0)
Enqueue (W, Q);
}
if (Counter ! = NumVertex)
Error(“Graph has a cycle”);
DisposeQueue(Q);
}
15 (a) (i) Algorithm to multiply n-digit integers using divide and conquer
approach?
Data Structures (Nov/Dec 2009) 2.67
Scheduling problem:
0 15 23 26 36
0 3 11 21 36
We can show that it will yield a optimal schedule. Let the jobs in the
schedule be ji1, ji2, …, jiN. The first job finishes in time ti1. The second
job finishes after ti1 + ti2 and third job finishes after ti1 + ti2 + ti3.
C = ∑ ( N − K + 1) tik
N
(1)
k =1
eqn (2) shows the first sum is independent of job ordering and second
sum affects the total cost. These result indicates that operating system
scheduler generally gives precedence to shorter jobs.
Huffman codes:
a 000 10 30
e 001 15 45
i 010 12 36
s 011 3 9
t 100 4 12
space 101 13 39
newline 110 1 3
174
Data Structures (Nov/Dec 2009) 2.69
a e i s t sp nl
The tree has data only in the leaves. This tree is encoded as 011. the
main question arise is now the tree is constructed. The algorithm to do
as Huffman code
T5 T4
T3
e i sp
T2
a
T1
t
s nl
2.70 B.E./B.Tech. Question Papers
15. (b) The adjacency matrix for the given traveling salesman problem is
1 2 3 4
1 0 10 15 20
2 5 0 9 10
3 6 13 0 12
4 8 8 9 0
To calculate optimal tour length,
g(2, f) = C21 = 5,
g(3, f) = C31 = 6,
g(4, f) = C41 = 8
The optimal tour of the graph has length 35. A tour of this length can
be constructed with each g(i, s), The value of j that minimizes the right
hand side of 1.
So the tour starts from 1 and go to 2. The remaining tour can be obtained
from g(2, {3, 4}). So (2, {3, 4}) = 4. Thus the next edge is (2, 4). The
remaining tour is for g(4, {3}) = 3.
The optimal tour is 1, 2, 4, 3, 1
Unsolved model paper 1
Part B (5 × 16 = 80 marks)
1. List out the areas in which data structures are applied extensively.
6. What is the bucket size, when the overlapping and collision occur at
same time?
7. Define graph.
Part B (5 × 16 = 80 marks)
11. (a) (i) What is a linked list? Explain with suitable program segments
any four operations of a linked list. (12)
(ii) Explain with a pseudo code how a linear queue could be
converted into a circular queue. (4)
Or
(b) (i) What is a stack ADT? Write in detail about any three applications
of stack. (11)
(ii) With a pseudo code explain how a node can inserted at a user
specified position of a doubly linked list. (5)
2.72 B.E./B.Tech. Question Papers
12. (a) (i) Discuss the various representations of a binary tree in memory
with suitable example. (8)
(ii) What are the basic operations that can be performed on a binary
tree? Explain each of them in detail with suitable example. (8)
Or
(b) (i) Give an algorithm to convert a general tree to binary tree. (8)
(ii) With an example, explain the algorithms of in order and post
order traversals on a binary search tree. (8)
13. (a) What is an AVL tree? Explain the rotations of an AVL tree. (16)
Or
(b) (i) Explain the binary heap in detail. (8)
(ii) What is hashing? Explain any two methods to overcome collision
problem of hashing. (8)
14. (a) (i) Explain Dijkstra’s algorithm and solve the single source shortest
path problem with an example. (12)
(ii) Illustrate with an example, the linked list representation of
graph. (4)
Or
(b) (i) Write the procedures to perform the BFS and DFS search of a
graph. (8)
(ii) Explain Prim’s algorithm to construct a minimum spanning tree
from an undirected graph. (8)
15. (a) (i) With an example, explain how will you measure the efficiency
of an algorithm. (8)
(ii) Analyze the linear search algorithm with an example. (8)
Or
(b) E
xplain how the travelling salesman problem can be solved using
greedy algorithm. (16)
Unsolved model paper 2
5. Convert the following infix expression into prefix and postfix notations
a * b − c − d + e * f − g h * i.
Part B (5 × 16 = 80 marks)
11. (a) (i) With an example, explain how will you measure the efficiency
of an algorithm. (8)
(ii) Analyze the linear search algorithm with an example. (8)
Or
(b) E
xplain the various aspects of problem solving in detail. Also discuss
pros and cons of each. (16)
12. (a) (i) Write suitable routines to perform insertion and deletion
operations in a linked queue. (12)
(ii) Write a suitable C routine to remove and return the top element
of the stack using Array implementation. (4)
2.74 B.E./B.Tech. Question Papers
Or
(b) W
rite suitable ADT operations to perform insertion and deletion in
a doubly linked list. (16)
13. (a) (i) Explain the various hashing techniques with suitable examples.
(10)
(ii) When will collisions arise? Discuss. (6)
Or
(b) W
rite suitable ADT’s to perform the following operations in an AVL
Tree.
(i) Insert a node. (8)
(ii) Delete a node. (8)
14. (a) W
rite ADT operations for Heap Sort. Also simulate the following
numbers using Heap Sort. What is the time complexity? (16)
6. What is hashing?
Part B (5 × 16 = 80 marks)
11. (a) Discuss in detail about the various aspects of problem solving. (16)
Or
(b) State and explain the algorithm to convert a decimal integer to its octal
equivalent. Trace the algorithm with an example. (16)
12. (a) G
iven a singly linked list L, formulate separate routines/algorithms
to
(i) insert an element X after a position P in the list. (8)
(ii) delete the first occurrence of an element Y from the list. Trace
the routine/algorithm with an example. (8)
2.76 B.E./B.Tech. Question Papers
Or
(b) (i) Formulate a routine in C/C + + to implement a stack using a
linked list and to pop an element from the stack. (8)
(ii) Write a routine to implement a queue using arrays and to
enqueue an element into it. (8)
13. (a) (i) Given an Unix file system as an input, formulate a routine to list
a directory. (8)
(ii) Write a routine/algorithm to insert an element into a binary
search tree. (8)
Or
(b) (i) Discuss in detail about the working of different hashing
functions. (10)
(ii) Write a function to perform deletion of an element from a binary
heap. (6)
14. (a) S
tate and explain the algorithm to perform Heap sort with an
example. (16)
Or
(b) S
tate and explain the algorithm to perform Merge sort with an
example. (16)
15. (a) S
tate the pseudo code for Dijkstra’s algorithm. Trace the algorithm
with an example. (16)
Or
(b) (i) State the Kruskal’s algorithm to compute the MST of a graph.
(ii) Write short notes on Biconnectivity. (16)