Professional Documents
Culture Documents
Cse-III-data Structures With C (10cs35) - Solution
Cse-III-data Structures With C (10cs35) - Solution
10CS35
Page 1
10CS35
malloc()
calloc()
Page 2
10CS35
Soln: Recursive function is a function which contains a call to itself. Recursive function
allows you to divide your complex problem into identical single simple cases which can
handle easily. This is also a well-known computer programming technique: divide and
conquer.
Recursion that only contains a single self-reference is known as single recursion, while
recursion that contains multiple self-references is known as multiple recursion. Standard
examples of single recursion include list traversal, such as in a linear search, or
computing the factorial function, while standard examples of multiple recursion
include tree traversal, such as in a depth-first search, or computing the Fibonacci
sequence.
Multiple recursion can sometimes be converted to single recursion (and, if desired, thence
to iteration). For example, while computing the Fibonacci sequence naively is multiple
iteration, as each value requires two previous values, it can be computed by single
recursion by passing two successive values as parameters.
direct recursion, in which a function calls itself. Indirect recursion occurs when a
function is called not by itself but by another function that it called (either directly or
indirectly). For example, if f calls f, that is direct recursion, but if f calls g which
calls f, then that is indirect recursion of f. Chains of three or more functions are possible;
for example, function 1 calls function 2, function 2 calls function 3, and function 3 calls
function 1 again.
Indirect recursion is also called mutual recursion, which is a more symmetric term,
though this is simply a different of emphasis, not a different notion. That is,
if f calls g and then g calls f, which in turn calls g again, from the point of view of f
alone, f is indirectly recursing, while from the point of view of g alone, it is indirectly
recursing, while from the point of view of both, f and g are mutually recursing on each
other. Similarly a set of three or more functions that call each other can be called a set of
mutually recursive functions.
#include<stdio.h>
int main(){
int a[10],i,n,m,c,l,u;
printf("Enter the size of an array: ");
scanf("%d",&n);
printf("Enter the elements of the array: " );
for(i=0;i<n;i++){
scanf("%d",&a[i]);
}
printf("Enter the number to be search: ");
scanf("%d",&m);
Dept. of CSE, SJBIT
Page 3
10CS35
l=0,u=n-1;
c=binary(a,n,m,l,u);
if(c==0)
printf("Number is not found.");
else
printf("Number is found.");
}
return 0;
if(l<=u){
mid=(l+u)/2;
if(m==a[mid]){
c=1;
}
else if(m<a[mid]){
return binary(a,n,m,l,mid-1);
}
else
return binary(a,n,m,mid+1,u);
}
else
return c;
5. What is dangling pointer reference & how to avoid it? (june/jul 2014)
Soln: Dangling pointers are pointers that do not point to a valid object of the
appropriate type. These are special cases ofmemory safety violations. More
generally, dangling references are references that do not resolve to a valid destination,
and include such phenomena as link rot on the internet. Dangling pointers arise
during object destruction, when an object that has an incoming reference is deleted or
deallocated, without modifying the value of the pointer, so that the pointer still points to
the memory location of the deallocated memory. As the system may reallocate the
previously freed memory to another process, if the original program then dereferences the
(now) dangling pointer,unpredictable behavior may result, as the memory may now
contain completely different data. This is especially the case if the program writes data to
memory pointed by a dangling pointer, a silent corruption of unrelated data may result,
leading to subtle bugs that can be extremely difficult to find, or cause segmentation
faults (UNIX, Linux) or general protection faults (Windows)
Page 4
10CS35
For example, we might say "this algorithm takes n2 time," where n is the number of items
in the input. Or we might say "this algorithm takes constant extra space," because the
amount of extra memory needed doesn't vary with the number of items processed.
Page 5
10CS35
For both time and space, we are interested in the asymptotic complexity of the algorithm:
When n (the number of items of input) goes to infinity, what happens to the performance
of the algorithm.
void add(int a[ ][MAX_SIZE], int b[ ][MAX_SIZE],
int c[ ][MAX_SIZE], int row, int cols )
{
int i, j;
for (i = 0; i < rows; i++){
count++; /* for i for loop */
for (j = 0; j < cols; j++) {
count++; /* for j for loop */
c[i][j] = a[i][j] + b[i][j];
count++; /* for assignment statement */
}
count++; /* last time of j for loop */
}
count++;
/* last time of i for loop */
}
Statement
s/e Frequency
Total steps
0
0
0
1
0
0
0
rows+1
0
0
0
rows+1
rows (cols+1)
rows cols+rows
1
0
rows cols
0
rows cols
0
{
int i, j;
for (i = 0; i < row; i++)
for (j=0; j< cols; j++)
c[i][j] = a[i][j] + b[i][j];
}
Total
2rows cols+2rows+1
Page 6
10CS35
return list[0];
2n+2
Statement
s/ e
0
0
1
1
1
0
0
0
n+1
n
1
0
2n+2
8. What is an ADT? Briefly explain the categories that classify the functions of a
data type. Write an ADT for natural number? (dec 2013/jan 2014)
Soln: An abstract data type(ADT) is a data type that is organized in such a way that the
specification of the objects and the operations on the objects is separated from the
representation of the objects and the implementation of the operations.
In computer science, an abstract data type (ADT) is a mathematical model for a certain
data structures that have similar behavior; or for certain data types of one or
more programming languages that have similar semantics. An abstract data type is
defined indirectly, only by the operations that may be performed on it and by
mathematical constraints on the effects (and possibly cost) of those operations. Abstract
Dept. of CSE, SJBIT
Page 7
10CS35
data types are purely theoretical entities, used (among other things) to simplify the
description of abstract algorithms, to classify and evaluate formally describe the type
systems of programming languages.
categories that classify the functions of a data type:
We type data--classify it into various categories--such as int, boolean, String,
Applet
A data type represents a set of possible values, such as {..., -2, -1, 0, 1, 2,
...}, or {true, false}
By typing our variables, we allow the computer to find some of our errors
Some operations only make sense when applied to certain kinds of data-multiplication, searching
Typing simplifies internal representation
A String requires more and different storage than a boolean
A data type is characterized by:
a set of values
a data representation, which is common to all these values, and
a set of operations, which can be applied uniformly to all these values
9. What is asymptotic notations & give the asymptotic representation of function 3n2 in all the three notations & prove the same from first principle method. (june/july
2013) (june/july 2015)
Soln: Asymptotic complexity is a way of expressing the main component of the cost of an
algorithm, using idealized units of computational work. Consider, for example, the
algorithm for sorting a deck of cards, which proceeds by repeatedly searching through the
deck for the lowest card. The asymptotic complexity of this algorithm is the square of the
number of cards in the deck. This quadratic behavior is the main term in the complexity
formula, it says, e.g., if you double the size of the deck, then the work is roughly
quadrupled.
Big Oh Notation (O)
Provides an upper bound for the function f
T(N) = O (f(N)) if there are positive constants c and n0 such that
T(N) cf(N) when N n0
growth rate of T(N) is less than or equal to growth rate of f(N) for large N
Omega Notation ()
10CS35
growth rate of T(N) is greater than or equal to growth rate of f(N) for large
N
Theta Notation ()
T(N) = (h(N)) if and only if
T(N) = O(h(N)) and T(N) = (h(N))
T(N) grows as fast as h(N)
growth rate of T(N) and h(N) are equal for large N
h(N) is a tight bound on T(N)
10. Explain the function supported by C to carryout dynamic memory allocation.
(June 2013)
Soln: C dynamic memory allocation refers to performing manual memory
management for dynamic memory allocation in the C programming languagevia a group
of functions in the C standard library, namely malloc, realloc,calloc and free.
Function Description
malloc
realloc
calloc
free
Page 9
10CS35
Space Complexity:
S(P)=C+SP(I)
instruction space
UNIT 2
ARRAYS and STRUCTURES
1. How does a structure differ from a union? Mention any 2 uses of structure.
What is a bit field? Why are bit fields used with structures? (June 2013)
Soln:
STRUCTURE
UNION
1. The keyword struct is used to define a
1. The keyword union is used to define a
structure.
union.
2. The size of the structure is greater or 2. The size of the union is equal to the size
Dept. of CSE, SJBIT
Page 10
10CS35
of the largest member.
3. Memory allocated is shared by
individual
members of the union.
4.Only one member can be accessed at a
time.
5.Altering the value of any of the member
will alter other member values.
Page 11
10CS35
}STUDENT;
STUDENT s[100];
2. With suitable example, explain dynamic memory allocation for 2-D arrays.
(june/jul 2014)
Soln: We've seen that it's straightforward to call malloc to allocate a block of memory
which can simulate an array, but with a size which we get to pick at run-time. Can we do
the same sort of thing to simulate multidimensional arrays? We can, but we'll end up
using pointers to pointers. If we don't know how many columns the array will have, we'll
clearly allocate memory for each row (as many columns wide as we like) by calling
malloc, and each row will therefore be represented by a pointer. How will we keep track
of those pointers? There are, after all, many of them, one for each row. So we want to
simulate an array of pointers, but we don't know how many rows there will be, either, so
we'll have to simulate that array (of pointers) with another pointer, and this will be a
pointer to a pointer.
This is best illustrated with an example:
#include <stdlib.h>
int **array;
array = malloc(nrows * sizeof(int *));
if(array == NULL)
{
fprintf(stderr, "out of memory\n");
exit or return
}
for(i = 0; i <nrows; i++)
{
array[i] = malloc(ncolumns * sizeof(int));
if(array[i] == NULL)
{
fprintf(stderr, "out of memory\n");
exit or return
}
}
array is a pointer-to-pointer-to-int: at the first level, it points to a block of pointers, one
for each row. That first-level pointer is the first one we allocate; it has n rows elements,
with each element big enough to hold a pointer-to-int, or int *. If we successfully allocate
it, we then fill in the pointers (all n rows of them) with a pointer (also obtained from
malloc) to n columns number of ints, the storage for that row of the array. If this isn't
quite making sense, a picture should make everything clear:
Page 12
10CS35
Page 13
10CS35
Soln:
#include <stdio.h>
#include <conio.h>
struct details
{
char name[30];
int age;
char address[500];
float salary;
char dept[30];
int emp_id;
char DOJ[20];
};
int main()
{
struct details detail;
clrscr();
printf("\nEnter name:\n");
gets(detail.name);
printf("\nEnter age:\n");
scanf("%d",&detail.age);
printf("\nEnter Address:\n");
gets(detail.address);
printf("\nEnter Salary:\n");
scanf("%f",&detail.salary);
printf("\nEnter dept, emp_id, DOJ);
scanf(%s%d%s, &detail.dept, &detail.emp_id,&detail.DOJ);
printf("\n\n\n");
printf("Name of the Employee : %s \n",detail.name);
printf("Age of the Employee : %d \n",detail.age);
printf("Address of the Employee : %s \n",detail.address);
printf("Salary of the Employee : %f \n",detail.salary);
printf("department of the Employee: %s\n",detail. Dept);
printf("ID of the Employee :%d\n,detail. emp_id);
printf(" Date of joining of the Employee: %s\n",detail.DOJ);
getch();
}
4. Write the fast transpose algorithm of a sparse matrix. Why the name fast
transpose? (june/jul 2014)
Page 14
10CS35
5.Develop a structure to represent planet in the solar system. Each planet has fields
for the planets name, its distance from the sun in miles & the number of moons it
has. Write a program to read the data for each planet & store. Also print the name
of the planet that has less distance from the sun. (dec 2013/jan 2014)
Soln:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
double const G = 6.672e-11; // Gravitational constant
double const MassSun = 2.0e30; // Sun's mass in kg
struct planet
{
char name[7];
double distance;
double mass;
double radius;
};
double density (struct planet *p);
double year(struct planet *p);
int main ()
{
Dept. of CSE, SJBIT
Page 15
10CS35
}
// Define the density function
double density (struct planet *p)
{
double result = (p->mass) / (( 4.0 * M_PI * pow(p->radius,3)) / 3.0);
return result;
}
// Define the year function
double year (struct planet *p)
{
double result = 2.0*M_PI*pow(p->distance, 1.5) / sqrt(G*MassSun);
return result;
}
Page 16
10CS35
Multiplication
... but not division!
Those rules keeps polynomials simple, so they are easy to work with!
function to add two polynomials
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct poly
{
int coeff;
Dept. of CSE, SJBIT
Page 17
10CS35
int exp;
struct poly *link;
};
struct poly *first,*second,*total;
void polyappend(struct poly **,int,int);
void polyadd(struct poly *,struct poly *,struct poly **);
void display(struct poly *);
void main()
{
int i=0,j=0,c,e,m,n;
first=second=total=NULL;
clrscr();
printf("enter the no of terms in the first polynomial");
scanf("%d",&n);
while(++i<=n)
{
printf("\n enter the coeff & exp of %d term",i);
scanf("%d%d",&c,&e);
polyappend(&first,c,e);
}
display(first);
printf("\n enter the no of terms in second polynomial");
scanf("%d",&m);
while(++j<=m)
{
printf("\n enter the coeff & exp of %d term",j);
scanf("%d%d",&c,&e);
polyappend(&second,c,e);
}
display(second);
polyadd(first,second,&total);
display(total);
}
void polyappend(struct poly **q,int x, int y)
{
struct poly *temp;
temp=*q;
if(*q==NULL)
{
*q=(struct poly *)malloc(sizeof(struct poly));
temp=*q;
}
else
{
while(temp->link!=NULL)
temp=temp->link;
Dept. of CSE, SJBIT
Page 18
10CS35
Page 19
10CS35
z->exp=x->exp;
x=x->link;
y= y->link;
}
}
while(x!=NULL)
{
if(*t==NULL)
{
*t=(struct poly *)malloc(sizeof(struct poly));
z=*t;
}
else
{
z->link=(struct poly *)malloc(sizeof(struct poly));
z=z->link;
}
z->coeff=x->coeff;
z->exp=x->exp;
x=x->link;
}
while(y!=NULL) {
if(*t==NULL)
{
*t=(struct poly *)malloc(sizeof(struct poly));
z=*t;
}
else
{
z->link=(struct poly *)malloc(sizeof(struct poly));
z=z->link;
}
z->coeff= y->coeff;
z->exp=y->exp;
y= y->link;
}
z->link=NULL; }
/***********INPUT- OUTPUT*************
Enter the no of terms in the first polynomial: 3
Enter the coeff & exp of 1 term: 2 3
Enter the coeff & exp of 2 term: 1 2
Enter the coeff & exp of 3 term: 4 1
2x ^ 3
1x^2
4x^1
Enter the no of terms in the second polynomial: 3
Enter the coeff & exp of 1 term: 2 3
Enter the coeff & exp of 2 term: 2 2
Dept. of CSE, SJBIT
Page 20
10CS35
7. For the given sparse matrix A & its transpose, give the triplet representation.
A is the given sparse matrix, & B will be its transpose.
15
0
0
22
0
-15
0
11
3
0
0
0
A=
0
0
0
-6
0
0
0
0
0
0
0
0
91
0
0
0
0
0
0
0
-28
0
0
0 (dec 2013/jan 2014) (june/jul
2015)
Soln: A<
6,
6,
8>
0
0
0
3
0
5
1
1
1
2
2
3
4
0
5
2
And its transpose is 15 0
0
0
22
0
-15
Its triplets
B
<6,
6
8>
0
0
15
0
4
91
1
1
11
2
1
3
2
5
-28
3
0
22
Dept. of CSE, SJBIT
15
22
-15
11
3
-6
91
-28
0
11
3
0
0
0
0
0
0
-6
0
0
91
0
0
0
0
0
0
0
0
0
0
0
0
-28
0
0
0
Page 21
2
-15
10CS35
-6
8.What is a structure ? Give three different ways of defining structure & declaring
variables & method of accessing members of structures using student structure with
roll number, names & marks in 3 subjects as members of that structure as example.
(june/july 2013) ((dec 2014/jan 2015) (june/jul 2014)
Soln: Structure:
A structure is a user-defined data type. You have the ability to define a new type of data
considerably more complex than the types we have been using. A structure is a collection
of one or more variables, possibly of different types, grouped together under a single
name for convenient handling. Structures are called records in some languages, notably
Pascal. Structures help organize complicated data, particularly in large programs, because
they permit a group of related variables to be treated as a unit instead of as separate
entities.
Todays application requires complex data structures to support them. Astructure
is a collection of related elements where element belongs to a different type.Another way
to look at a structure is a template a pattern. For example graphical userinterface found
in a window requires structures typical example for the use of structurescould be the file
table which holds the key data like logical file name, location of the fileon disc and so on.
The file table in C is a type defined structure - FILE.Each element of a structure is also
called as field. A field has a manycharacteristic similar to that of a normal variable. An
array and a structure are slightlydifferent. The former has a collection of homogeneous
elements but the latter has acollection of heterogeneous elements. The general format for
a structure in C is shown
struct{field_list} variable_identifier;
structstruct_name
{
type1 fieldname1;
type2 fieldname2;
.
.
.
typeNfieldnameN;
};
structstruct_name variables;
The above format shown is not concrete and can vary, so different `
flavours of structure declaration is as shown.
struct
{
.
} variable_identifer;
Example
structmob_equip;
Dept. of CSE, SJBIT
Page 22
10CS35
{
long int IMEI;
char rel_date[10];
char model[10];
char brand[15];
};
The above example can be upgraded with typedef. A program to illustrate the
working of the structure is shown in the previous section.
typedefstructmob_equip;
{
long int IMEI;
char rel_date[10];
char model[10];
char brand[15];
int count;
} MOB; MOB m1;
structtag
{
.
};
structtag variable_identifers;
typedefstruct
{
..
} TYPE_IDENITIFIER;
TYPE_IDENTIFIER variable_identifers;
Accessing a structure
A structure variable or a tag name of a structure can be used to access themembers of a
structure with the help of a special operator . also called as memberoperator . In our
previous example To access the idea of the IMEI of the mobileequipment in the structure
mob_equip is done like thisSince the structure variable can be treated as a normal
variable All the IOfunctions for a normal variable holds good for the structure variable
also with slight. Thescanf statement to read the input to the IMEI is given below
scanf (%d,&m1.IMEI);
Increment and decrement operation are same as the normal variables thisincludes postfix
and prefix also. Member operator has more precedence than theincrement or decrement.
Say suppose in example quoted earlier we want count ofstudent then
m1.count++; ++m1.count
Page 23
10CS35
9. Give ADT sparser matrix & show with a suitable example sparse matrix
representation storing as triplets. Give simple transpose function to
transpose sparse matrix & give its complexity. (june/july 2013)
Soln:
Objects: a set of triples, <row, column, value>, where row
and column are integers and form a unique combination, and
value comes from the set item.
Methods:
for all a, b Sparse_Matrix, x item, i, j, max_col,
max_row index
Sparse_Marix Create(max_row, max_col) ::=
return a Sparse_matrix that can hold up to
max_items = max _row max_col and
whose maximum row size is max_row and
whose maximum column size is max_col
Sparse_Matrix Transpose(a) ::=
return the matrix produced by interchanging
the row and column value of every triple.
Sparse_Matrix Add(a, b) ::=
if the dimensions of a and b are the same
return the matrix produced by adding
corresponding items, namely those with
identical row and column values.
else return error
Sparse_Matrix Multiply(a, b) ::=
Dept. of CSE, SJBIT
Page 24
10CS35
if number of columns in a equals number of rows in
return the matrix d produced by multiplying
a by b according to the formula: d [i] [j] =
S(a[i] [k] b[k] [j] ) where d (i, j) is the (i,j)th
element
else return error.
[1]
[2]
[3]
[5]
[6]
[7]
[8]
Page 25
10CS35
/* transpose by columns in a */
for( j = 1; j <= n; j++)
/* find elements from the current column */
if (a[j] .col == i) {
/* element is in current column, add it to b */
10.How would you represent two sparse polynomials using array of structure & also
write a function to add that polynomials & store the result in the same array.
(june/july 2013)
Soln: Sparse Polynomial representation and addition:
Polynomial is an expression which is composed of terms, wherein terms are composed of
coefficient and exponent. An example of a polynomial is: 4x3+5x2+6x+9. This
polynomial is composed of four terms with the following sets of coefficient and exponent
{(4,3), (5,2), (6,1), (9,0)}. Thus representation of a polynomial using arrays is
straightforward. The subscripts of the array may be considered as exponents and the
coefficients may be stored at an appropriate place referred to by the subscript. Array
representation for the above example is:
arr:
subscripts: 0
6
1
5
2
4
3
coefficients
exponents
The above representation works fine for the above example, but for polynomials such as
56+7, array representation is considered feasible on account of memory usage, since it
results in a sparse arrangement as follows:
arr 7
0
1
2
3
4
5
6 (Subscripts)
Sparse matrix representation may be considered for the above matrix as given below:
Rows
Cols
Value
(Total)
For addition of two polynomials using arrays, subscript-wise elements may be added to
result in the polynomial containing result of addition of two polynomials.
Dept. of CSE, SJBIT
Page 26
10CS35
Example:
Polynomial 1:
4x3 + 5x2 + 6x + 7
Polynomial 2:
3x3 + 4x2 + 2x + 2
7x3 + 9x2 + 8x + 9
Array Representation:
Subscripts:
Polynomial 1:
Polynomial 2:
Result of sum: 9
Page 27
10CS35
Page 28
10CS35
UNIT 3
STACKS AND QUEUES
1. Write an algorithm to convert a valid infix expression to a postfix expression. Also
evaluate the following suffix expression for the values: A=1 B=2 C=3.
AB+C-BA+C$- and convert i) a*(b+c)*d
ii) (a+b)*d+e/(f+a*d)+c
iii) ((a/(b-c+d))*(e-a)*c)
iv) a/b-c+d*e-a*c iv) (a*b) +c/d
v) ((a/b)c)+(d*e)) (a*c) to postfix. (june/jul 2014) (dec 2013/jan 2014) (June 2013)
(june/july 2013) (Dec 2014/Jan 2015) (june/jul 2015)
Soln:
Page 29
10CS35
Page 30
10CS35
queue where priority is the same for all the jobs and whichever job is submitted first, that
job will be processed.
Priority queues are used in designing CPU schedulers where jobs are dispatched to the
CPU based on priority of the job.
Algorithm CQINSERT for static implementation of circular queue Step 1 : Check for overflow : This is achieved using the following statementsif(count ==
queue_size)
{
printf(Queue is full\n);
return;
}
Step 2: Insert item : This is achieved by incrementing r by 1 and then inserting as shown
belowr
= (r+1)%queue_size;
q[r] = item;
Step 3: Update count : As we insert an element, update count by 1. This is achieved
using the following statementcount++;
3. How multiple stacks implemented using one dimensional array? Explain with a
suitable example. (june/jul 2014)
Soln:
4. Define stack. Implement push & pop functions for stack using arrays. (dec
2013/jan 2014) (Dec 2014/Jan 2015) (June 2013)
Soln: A stack is an ordered collection of items into which new items may be inserted and
from which items may be deleted at one end, called the top of the stack. A stack is a
dynamic, constantly changing object as the definition of the stack provides for the
insertion and deletion of items. It has single end of the stack as top of the stack, where
both insertion and deletion of the elements takes place. The last element inserted into the
stack is the first element deleted-last in first out list (LIFO). After several insertions and
deletions, it is possible to have the same frame again.
Primitive Operations
When an item is added to a stack, it is pushed onto the stack. When an item is removed, it
is popped from the stack.
Given a stack s, and an item i, performing the operation push(s,i) adds anitem i to the top
of stack s.
push(s, H);
push(s, I);
push(s, J);
Page 31
10CS35
Operation pop(s) removes the top element. That is, if i=pop(s), then theremoved element
is assigned to i.
pop(s);
Because of the push operation which adds elements to a stack, a stack issometimes called
a pushdown list. Conceptually, there is no upper limit on the number of items that may be
keptin a stack.If a stack contains a single item and the stack is popped, the resulting
stackcontains no items and is called the empty stack. Push operation is applicable to any
stack. Pop operation cannot be applied tothe empty stack. If so, underflow happens. A
Boolean operation empty(s), returnsTRUE if stack is empty. Otherwise FALSE, if stack
is not empty.
Representing stacks in C
Before programming a problem solution that uses a stack, we must decidehow to
represent the stack in a programming language. It is an ordered collectionof items. In C,
we have ARRAY as an ordered collection of items. But a stackand an array are two
different things. The number of elements in an array isfixed. A stack is a dynamic object
whose size is constantly changing. So, an arraycan be declared large enough for the
maximum size of the stack. A stack in C isdeclared as a structure containing two objects:
An array to hold the elements of the stack.
An integer to indicate the position of the current stack top within the array.
#define STACKSIZE 100
struct stack {
int top;
int items[STACKSIZE];
};
The stack s may be declared by
struct stack s;
The stack items may be int, float, char, etc. The empty stack contains noelements and can
therefore be indicated by top= -1. To initialize a stack S to theempty state, we may
initially execute
s.top= -1.
To determine stack empty condition,
if (s.top=-1)
stack empty;
else
stack is not empty;
The empty(s) may be considered as follows:
int empty(struct stack *ps)
{
if(ps->top== -1)
return(TRUE);
else
return(FALSE);
}
Aggregating the set of implementation-dependent trouble spots into small,easily
identifiable units is an important method of making a program moreunderstandable and
modifiable. This concept is known as modularization, inwhich individual functions are
Dept. of CSE, SJBIT
Page 32
10CS35
isolated into low-level modules whose propertiesare easily verifiable. These low-level
modules can then be used by more complexroutines, which do not have to concern
themselves with the details of the low-level modules but only with their function. The
complex routines maythemselves then be viewed as modules by still higher-level routines
that use themindependently of their internal details.
Implementing pop operation
If the stack is empty, print a warning message and halt execution. Remove thetop element
from the stack. Return this element to the calling program
int pop(struct stack *ps)
{
if(empty(ps)){
printf(%,stack underflow);
exit(1);
}
return(ps->items[ps->top--]);
}
5. Give ADT stack & with necessary function, explain implementing stacks to hold
records with different type of fields in stack. (june/july 2013)
Soln: A stack is an ordered collection of items into which new items may be inserted and
from which items may be deleted at one end, called the top of the stack. A stack is a
dynamic, constantly changing object as the definition of the stack provides for the
insertion and deletion of items. It has single end of the stack as top of the stack, where
both insertion and deletion of the elements takes place. The last element inserted into the
stack is the first element deleted-last in first out list (LIFO). After several insertions and
deletions, it is possible to have the same frame again.
6. Obtain the postfix and prefix expression for (((A+(B-C)*D) E)+F). (Jan 2013)
Soln: prefix: +*+a*-bcdef and postfix: abc-d*+e*f+
7. What is system stack? How the control is transferred to or from the function with
the help of activation record? (Jan 2013)
Soln: Before programming a problem solution that uses a stack, we must decidehow to
represent the stack in a programming language. It is an ordered collectionof items. In C,
we have ARRAY as an ordered collection of items. But a stackand an array are two
different things. The number of elements in an array isfixed. A stack is a dynamic object
whose size is constantly changing. So, an arraycan be declared large enough for the
maximum size of the stack. A stack in C isdeclared as a structure containing two objects:
An array to hold the elements of the stack.
UNIT 4
Dept. of CSE, SJBIT
Page 33
10CS35
LINKED LISTS
1. List out any two applications of linked list and any two advantages of doubly
linked list over singly linked list. (june/jul 2014)
Soln: Applications of linked list:
Arithmetic operations can be easily performed on long positive numbers.
Manipulation and evaluation of polynomials is easy.
Useful in symbol table construction(Compiler design).
Advantages of doubly linked list over singly linked list:
2. Define doubly linked list. Write a c program to perform the following operations
on doubly linked list : i) insert a node ii) delete a node. (june/july 2013)
Soln: Although a circularly linked list has advantages over linear lists, it still has some
drawbacks. One cannot traverse such a list backward. Double-linked lists require more
space per node , and their elementary operations are more expensive; but they are often
easier to manipulate because they allow sequential access to the list in both directions. In
particular, one can insert or delete a node in a constant number of operations given only
that node's address. (Compared with singly-linked lists, which require the previous node's
address in order to correctly insert or delete.) Some algorithms require access in both
directions. On the other hand, they do not allow tail-sharing, and cannot be used as
persistent data structures.
i)void insert_at_left(int id)
{
struct node *cur=first,*prev=NULL,*newnode;
newnode=getnode();
if(first->data==id)
{
newnode->right=first;
first->left=newnode;
first=newnode;
}
while(cur!=NULL)
Dept. of CSE, SJBIT
Page 34
10CS35
if(cur->data==id)
{
prev->right=newnode;
cur->left=newnode;
newnode->left=prev;
newnode->right=cur;
}
prev=cur;
cur=cur->right;
}}
ii)void delete(int id)
{
struct node *cur=first,*prev=NULL;
if(first->data==id)
{
prev=first;
first=first->right;
first->left=NULL;
free(prev);
return;
}
while(cur!=NULL)
{
if(cur->data==id)
{
prev->right=cur->right;
cur->right->left=prev;
free(cur);
return;
}
else
{
prev=cur;
cur=cur->right;
}
}
}
3. Write short note on circular lists. Write a function to insert a node at front and
rear end in a circular linked list. Write down sequence of steps to be followed.
(june/jul 2015)
Soln: A popular convention is to have the last cell keep a pointer back to the first. This
can be done with or without a header (if the header is present, the last cell points to it),
and can also be done with doubly linked lists (the first cell's previous pointer points to the
Page 35
10CS35
last cell). This clearly affects some of the tests, but the structure is popular in some
applications. Figure 3.17 shows a double circularly linked list with no header.
Page 36
10CS35
Page 37
10CS35
Suppose we want to insert a new node at the front of this list. We have to change the
LINK field of the node containing x3. This requires that we move down the entire length
of A until we find the last node. It is more convenient if the name of a circular list points
to the last node rather than the first.
5. Write the node structure for linked representation of polynomial. Explain the
algorithm to add two polynomial represented using linked lists. (june/jul 2014)
(june/july 2013) (June 2013)
Soln:
6. Write the different polynomial representation, with an example. (dec 2013/jan
2014)
Soln:
7. For the given sparse matrix. write the diagrammatic linked representation. (dec
2013/jan 2014) (june/july 2013)
5
0
0
0
3
0
0
1
A=
0
0
0
0
8
0
0
2
0
0
7
0
Soln:
8. Define equivalence class. Write the linked list representation for the twelve
polygons numbered 0 through 11 using the following pairs overlap?
04, 31, 610, 8 9, 7 4, 6 8, 33, 2 11, 11 0 (dec 2013/jan 2014)
Soln:
9. What is a linked list? Explain the different types of linked list with diagram.
Write C program to implement the insert and delete operation on a queue using
linked list. (dec 2013/jan 2014) (June 2013) (dec 2014/jan 2015)
Soln:
procedure INSERT__FRONT(A, X)
//insert the node pointed at by X to the front of the circular list
A, where A points to the last node//
if A = 0 then [A X
LINK (X) A]
else [LINK(X) LINK (A)
LINK(A) X]
end INSERT--FRONT
To insert X at the rear, one only needs to add the additional statement A X to the else
clause of INSERT_-_FRONT.
Page 38
10CS35
PART B
Unit 5
TREES 1
ii)Complete binary tree - A strictly binary tree in which the number of nodes at any
level i is 2i, is said to be a complete binary tree.
Ex:
iii) Almost complete binary tree - A tree of depth d is an almost complete binary tree
Dept. of CSE, SJBIT
Page 39
10CS35
if following two properties are satisfied 1. If the tree is complete upto the level d-1, then the total number of nodes at the level
d-1 shoud be 2d-1 .
2. The total number of nodes at level d may be equal to 2d. If the total number of
nodes at level d is less than 2d, then the number of nodes at level d-1 should be 2d-1
and in level d the nodes should be present only from left to right.
ex:
iv)Binary search tree A binary search tree is a binary tree in which for each node
say x in the tree, elements in the left sub-tree are less than info(x) and elements in the
right sub-tree are greater than or equal to info(x). Every node in the tree should
satisfy this condition, if left sub-tree or right sub-tree exists.
Ex:
v)Depth of a tree Depth of a tree is defined as the length of the longest path from
root to a leaf of the tree. Length of a path is the number of branches encountered
while traversing the path.
Ex:
Page 40
10CS35
2. What is threaded binary tree? Explain right in and left in threaded binary trees.
Advantages of TBT over binary tree. (june/jul 2014) (Dec 2014/Jan 2015)
Soln: Threaded binary tree The link fields in a binary tree which contain NULL values
can be replaced by address of some nodes in the tree which facilitate upward movement
in the tree. These extra links which contain addresses of some nodes are called threads
and the tree is termed as threaded binary tree.
In-threaded binary tress - In a binary tree, if llink of any node contains null and if it is
replaced by address of inorder predecessor, then the resulting tree is called left inthreaded
binary tree. If rlink of a node is null and if it is replaced by address of inorder sucessor,
the resulting tree is called right inthreaded tree. A inthreaded binary tree is one which is
both left and right in-threaded.
EX: Right in-threaded binary tree:
Page 41
10CS35
procedure preorder(x){
visit(x)
i=1; while( i <= degree() ){
preorder( child(i) )
}
}
Postorder
procedure postorder(x){
i=1; while( i <= degree() ){
postorder( child(i) )
}
visit(x)
Dept. of CSE, SJBIT
Page 42
Inorder
10CS35
}
procedure inorder(x){
if( left_child_for(x) ) { inorder( left_child(x) ) }
visit(x)
if( right_child_for(x) ) { inorder( right_child(x) ) }
}
4. For any nonempty binary tree T, if n0 is the number of leaf nodes & n2 the
number of nodes of degree 2, then prove that n0=n2+1. (june/jul 2014)
Soln:
5. What is a binary tree? State its properties ? How it is represented using array &
linked list, give example. (dec 2013/jan 2014) (june/july 2013)
Soln:
6. Define a max heap? Write a C function to insert an item into max heap? (dec
2013/jan 2014) (june/july 2013)
Soln:
7.what is a heap? Explain the different types of heap? (june/july 2015)
Soln:
A heap is a complete tree with an ordering-relation R holding between each node and its
descendant.
Examples for R: smaller-than, bigger-than
Assumption: In what follows, R is the relation bigger-than, and the trees have degree 2.
Heap
Not a heap
Adding an Element
1. Add a node to the tree
Page 43
10CS35
2. Move the elements in the path from the root to the new node one position down, if
they are smaller than the new element
new element
modified tree
4. A complete tree of n nodes has depth log n , hence the time complexity is O(log
n)
Deleting an Element
1. Delete the value from the root node, and delete the last node while saving its
value.
before
after
8. define binary trees. For the given tree find the following : (June 2013) (june/july
2015)
i.
siblings
ii.
leaf nodes
iii. non leaf nodes
iv.
ancestors
Dept. of CSE, SJBIT
Page 44
10CS35
level of trees
Soln:
Unit 6
TREES 2, GRAPHS
1. Explain the following with an example: i) forest & its traversals. Explain the
different method of traversing a tree with following tree
ii) graph iii) winner tree .iv) Selelction trees(dec 2013/jan 2014) (June 2013)
(june/jul 2015).
Soln:
2. Describe the binary search tree with an example. Write a iterative & recursive
function to search for a key value in a binary search tree. Define ADT of binary
search tree. Write BST for the elements { 22,28,20,25,22,15,18,10,14} {14, 5, 6, 2,
18, 20, 16, 18, -1, 21} . (Jan 2013)
(june/jul 2014). (dec 2013/jan 2014) (june/july 2013) (June 2013) (june/jul 2014).
Soln:
3. Explain selection trees, with suitable example. (june/jul 2014)
Soln:
4. What is a forest. With suitable example illustrate how you transform a forest into
a binary tree. (june/jul 2014)
Soln:
Dept. of CSE, SJBIT
Page 45
10CS35
5. Write the adjacency matrix & adjacency list for the following graph(dec 2013/jan
2014)
Soln:
6. What is a winner tree ? Explain with suitable example a winner tree for k=8.
(june/july 2013) (june/jul 2015).
Soln:
7. Construct a binary tree having the following sequences. (june/july 2013) (June
2013) (dec 2014/jan 2015) (june/july 2014)
i) Preorder sequence: ABCDEFGHI
ii) Inorder sequence: BCAEDGHFI
1) pre order: /+*1 $ 2 3 4 5
ABDGCEHIF
2) IN ORDER :
1+2*3$45
DGBAHEICE
Soln:
8. Give the adjacency matrix & adjacency lists representation for the graph shown
below: (june/july 2013)
Soln:
UNIT 7
PRIORITY QUEUES
1. What is binomial heap? Explain the steps involved in the deletion of min
element from a binomial heap.insertion into binomial heaps. Melding 2
Dept. of CSE, SJBIT
Page 46
10CS35
binomial heaps. (june/jul 2014) (dec 2013/jan 2014) (Dec 2014/Jan 2015)
(June 2013)
Soln: Binomial heap is a heap similar to a binary heap but also supports quickly merging
two heaps. This is achieved by using a special tree structure. It is important as an
implementation of the mergeable heap abstract data type (also called meldable heap),
which is a priority queue supporting merge operation. A binomial heap is implemented as
a collection of binomial trees (compare with a binary heap, which has a shape of a single
binary tree).
Delete minimum
To delete the minimum element from the heap, first find this element, remove it from
its binomial tree, and obtain a list of its subtrees. Then transform this list of subtrees into
a separate binomial heap by reordering them from smallest to largest order. Then merge
this heap with the original heap. Since each tree has at most log n children, creating this
new heap is O(log n). Merging heaps is O(log n), so the entire delete minimum operation
is O(log n).
function deleteMin(heap)
min = heap.trees().first()
for each current in heap.trees()
if current.root < min then min = current
for each tree in min.subTrees()
tmp.addTree(tree)
heap.removeTree(min)
merge(heap, tmp)
2. Define Fibonacci heap. Briefly explain the different types. (dec 2013/jan 2014).
(June 2015)
Soln: A Fibonacci heap is a heap data structure consisting of a collection of trees. It has
a better amortized running time than a binomial heap. Fibonacci heaps were developed by
Michael L. Fredman and Robert E. Tarjan in 1984 and first published in a scientific
journal in 1987. The name of Fibonacci heap comes from Fibonacci numbers which are
used in the running time analysis.
3.Explain priority queue? Explain the various types of priority queues .List the
single ended & double ended priority queue operations. (june/jul 2014) (dec
2013/jan 2014) (june/july 2013) (June 2013)
Soln: It is a collection of ordered elements that provides fast access to the
minimum or maximum element.
Basic Operations performed by priority queue are:
Dept. of CSE, SJBIT
Page 47
10CS35
1.Insert operation
2.Delete min operation
Insert operation is the equivalent of queues Enqueue operation.
DeleteminoperationisthepriorityqueueequivalentofthequeuesDequeue operation.
Deltemin(H)
PriorityQueueH
Insert(H)
Implementation:
Therearethreewaysforimplementingpriorityqueue.Theyare:
1.Linkedlist
2.BinarySearchtree
3.BinaryHeap
Single- and Double-Ended Priority Queues:
A (single-ended) priority queue is a data type supporting the following operations on an
ordered set of
values:
1) find the maximum value (FindMax);
2) delete the maximum value (DeleteMax);
3) add a new value x (Insert(x)).
Obviously, the priority queue can be redefined by substituting operations 1) and 2) with
FindMin and
DeleteMin, respectively. Several structures, some implicitly stored in an array and some
using more complex data structures, have been presented for implementing this data type,
including max-heaps (or min-heaps)
Conceptually, a max-heap is a binary tree having the following properties:
a) heap-shape: all leaves lie on at most two adjacent levels, and the leaves on the last
level occupy the leftmost positions; all other levels are complete.
b) max-ordering: the value stored at a node is greater than or equal to the values stored at
its children. A max-heap of size n can be constructed in linear time and can be stored in
an n-element array; hence it is referred to as an implicit data structure [g].
When a max-heap implements a priority queue, FindMax can be performed in constant
time, while both DeleteMax and Insert(x) have logarithmic time. We shall consider a
more powerful data type, the double-ended priority queue, which allows both FindMin
and FindMax, as well as DeleteMin, DeleteMax, and Insert(x) operations. An important
application of this data type is in external quicksort .
A traditional heap does not allow efficient implementation of all the above operations; for
example, FindMin requires linear (instead of constant) time in a max-heap. One approach
to overcoming this intrinsic limitation of heaps, is to place a max-heap back-to-back
with a min-heap.
Definition
A double-ended priority queue (DEPQ) is a collection of zero or more elements. Each
Dept. of CSE, SJBIT
Page 48
10CS35
Page 49
10CS35
of the min PQ and the max PQ that contain the same element. Figure 1 shows a dual heap
structure for the elements 6, 7, 2, 5, 4. Correspondence pointers are shown as red arrows.
Page 50
10CS35
Notation. Let the s-value of a node be the shortest distance from the node to an external
node.
x
x
5. Briefly explain the following with an example :i) HBLT ii) WBLT (dec 2013/jan
2014) (june/july 2013)
Dept. of CSE, SJBIT
Page 51
10CS35
Soln:
6. What is Fibonacci heap? Give suitable example & give the steps for deletion of
node & decrease key of specified node in F- heap. (june/july 2013) (Dec 2014/Jan
2015) (June 2013)
Soln: A Fibonacci heap is a heap data structure consisting of a collection of trees. It has
a better amortized running time than a binomial heap. Fibonacci heaps were developed by
Michael L. Fredman and Robert E. Tarjan in 1984 and first published in a scientific
journal in 1987. The name of Fibonacci heap comes from Fibonacci numbers which are
used in the running time analysis.
Find-minimum is O(1) amortized time.Operations insert, decrease key, and merge
(union) work in constant amortized time. Operations delete and delete minimum work in
O(log n) amortized time. This means that starting from an empty data structure, any
sequence of a operations from the first group and b operations from the second group
would take O(a + b log n) time. In a binomial heap such a sequence of operations would
take O((a + b)log (n)) time. A Fibonacci heap is thus better than a binomial heap when b
is asymptotically smaller than a.
Figure 1. Example of a Fibonacci heap. It has three trees of degrees 0, 1 and 3. Three
vertices are marked (shown in blue). Therefore the potential of the heap is 9.
A Fibonacci heap is a collection of trees satisfying the minimum-heap property, that is,
the key of a child is always greater than or equal to the key of the parent. This implies
that the minimum key is always at the root of one of the trees. Compared with binomial
heaps, the structure of a Fibonacci heap is more flexible. The trees do not have a
prescribed shape and in the extreme case the heap can have every element in a separate
tree. This flexibility allows some operations to be executed in a "lazy" manner,
postponing the work for later operations. For example merging heaps is done simply by
concatenating the two lists of trees, and operation decrease key sometimes cuts a node
from its parent and forms a new tree.
UNIT-8
EFFICIENT BINARY SEARCH TREES
Page 52
10CS35
1. Describe the following with an eg: i) height balanced trees ii) optimal bst. iii) AVL
trees & Write the algorithm to insert an item into AVL tree. Perfor m the following
insertions in sequence MARCH, MAY, NOVEMBER, AUGUST, APRIL,
JANUARY, DECEMBER, JULY, FEBRUARY,.(dec 2013/jan 2014) (june/jul 2014)
(june/july 2013) (June 2013) ,.(dec 2014/jan 2015) (june/july 2015)
Soln: Trees of height O(log n) are said to be balanced. AVL trees consist of a special
case in which the subtrees of each node differ by at most 1 in their height. Balanced trees
can be used to search, insert, and delete arbitrary keys in O(log n) time.
2. Explain the Red-black tree. State its properties. Insert the following keys in the
given order { 50,10,80,90,70,60,65,62} giving color changing & rotation instances.
(june/jul 2014) (dec 2013/jan 2014) (june/july 2013) (June 2013) ,.(dec 2014/jan
2015) (june/july 2015)
Soln: A binary search tree in which
x
x
x
Empty subtrees of a node are treated as subtrees with roots of black color.
The relation n > 2h/2 - 1 implies the bound h < 2 log 2(n + 1).
3. What is splay tree? Briefly explain the different types of splay trees. (june/jul
2014) (dec 2013/jan 2014) June 2012)
Soln: Splay Trees (self-adjusting search trees):
These notes just describe the bottom-up splaying algorithm, the proof of the
access lemma, and a few applications. Every time a node is accessed in a splay
tree, it is moved to the root of the tree. The amortized cost of the operation is
O(log n). Just moving the element to the root by rotating it up the tree does not
have this property. Splay trees do movement is done in a very special way that
guarantees this amortized bound.
y
Zig (terminal case):
x
z
/
Dept. of CSE, SJBIT
x
/ ====>
y
z
x
Page 53
Zig-zig:
\
x
z
/
/
x
====> x ====>
/
y z
y
x
y
\
====> / \ ====>
x z
\
z
10CS35
/\
Page 54