Download as pdf or txt
Download as pdf or txt
You are on page 1of 54

DATA STRUCTURES WITH C

10CS35

VTU QUESTION BANK SOLUTIONS


PART A
UNIT 1
BASIC CONCEPTS
1. What is a pointer variable? How pointers are declared & initialized in C? Can we
have multiple pointer to a variable? Explain Lvalue and Rvalue expression.(june/jul
2014) (june/july 2013) (Dec 2014/Jan 2015)
Soln: A variable which holds the address of another variable is called a pointer variable.
In other words, pointer variable is a variable which holds pointer value (i.e., address of a
variable.)
ex: int *p; /*declaration of a pointer variable */
int a=5;
p = &a;
Yes, we can have multiple pointers to a variable.
Ex: int *p , *q , *r;
int a=10;
p = &a;
q = &a;
r = &a;
Here, p ,q, r all point to a single variable 'a'.An object that occurs on the left hand side of
the assignment operator is called Lvalue. In other words, Lvalue is defined as an
expression or storage location to which a value can be assigned.Ex: variables such as
a,num,ch and an array element such as a[0], a[i], a[i][j] etc.
Rvalue refers to the expression on right hand side of the assignment operator. The R in
Rvalue indicates read the value of the expression or read the value of the variable.
Ex: 5, a+2, a[2]+4, a++, --y etc.
2. Give atleast 2 differences between : i. Static memory allocation and dynamic
memory allocation.
ii. Malloc() and calloc(). (Dec 2014/Jan 2015)
Soln:
Static memory allocation
Dynamic memory allocation
1.Memory is allocated during compilation 1. Memory is allocated during execution
time.
time.
2. Used only when the data size is fixed
and known in advance before processing.

Dept. of CSE, SJBIT

2. Used only for unpredictable memory


requirement.

Page 1

DATA STRUCTURES WITH C

10CS35

malloc()

calloc()

1.The syntax of malloc() is:


ptr = (data_type*)malloc(size);
The required number of bytes to be
allocated is specified as argument i.e.,
size in bytes.
2. Allocated space will not be initialized.

1.The syntax of calloc() is:


ptr = (data_type*)calloc(n,size);
takes 2 arguments n number of blocks
to be allocated and size is number of
bytes to be allocated for each block.
2. Each byte of allocated space is initialized
to zero.

3. i) Write a C program using pass by reference method to swap 2 characters.


ii) Give any 2 advantages and disadvantages of using pointers. (June/july 2013)
Soln: i) #include<stdio.h>
void swap(char *a, char *b)
{
char c;
c = *a;
*a = *b;
*b = c;
}
void main()
{
char m,n;
printf(Enter 2 characters\n);
scanf(%c%c,&m,&n);
printf(Before swapping\n);
printf(m = %c, n = %c\n,m,n);
swap(&m,&n);
printf(After swapping\n);
printf(m = %c, n = %c\n,m,n);
}
ii) Advantages of using pointers:
* More than one value can be returned using pointer concept(pass by reference).
* Data accesing is much faster when compared to arrays.
Disadvantages of using pointers;
Un-initialized pointers or pointers containing invalid addresses can cause system crash.
They are confusing and difficult to understand in the beginning and if they are misused,
the result is not predictable.
4. Define Recursion. What are the various types of recursion? Give two conditions
to be followed for successive working of recursive program. Give recursive
implementation of binarys search with proper comments. (june/july 2013)
(june/july 2015) (Dec 2014/Jan 2015)
Dept. of CSE, SJBIT

Page 2

DATA STRUCTURES WITH C

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

DATA STRUCTURES WITH C

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;

int binary(int a[],int n,int m,int l,int u){


int mid,c=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)

Dept. of CSE, SJBIT

Page 4

DATA STRUCTURES WITH C

10CS35

Avoiding: In C, the simplest technique is to implement an alternative version of


the free() (or alike) function which guarantees the reset of the pointer. However, this
technique will not clear other pointer variables which may contain a copy of the pointer.
These uses can be masked through #define directives to construct useful macros, creating
something like a metalanguage or can be embedded into a tool library apart. In every
case, programmers using this technique should use the safe versions in every instance
where free() would be used; failing in doing so leads again to the problem. Also, this
solution is limited to the scope of a single program or project, and should be properly
documented. Another approach is to use the Boehm garbage collector, a
conservative garbage collector that replaces standard memory allocation functions in C
and C++ with a garbage collector. This approach completely eliminates dangling pointer
errors by disabling frees, and reclaiming objects by garbage collectoion.
6. Define the term space & time complexity. Apply program step counter method
to estimate the time complexity of a function to add two matrices. (june/jul
2014)(dec 2013/jan 2014)
Soln: The complexity of an algorithm is a function describing the efficiency of the
algorithm in terms of the amount of data the algorithm
Time complexity is a function describing the amount of time an algorithm takes in terms
of the amount of input to the algorithm. "Time" can mean the number of memory
accesses performed, the number of comparisons between integers, the number of times
some inner loop is executed, or some other natural unit related to the amount of real time
the algorithm will take. We try to keep this idea of time separate from "wall clock" time,
since many factors unrelated to the algorithm itself can affect the real time (like the
language used, type of computing hardware, proficiency of the programmer, optimization
in the compiler, etc.). It turns out that, if we chose the units wisely, all of the other stuff
doesn't matter and we can get an independent measure of the efficiency of the algorithm.
x

Space complexity is a function describing the amount of memory (space) an


algorithm takes in terms of the amount of input to the algorithm. We often speak
of "extra" memory needed, not counting the memory needed to store the input
itself. Again, we use natural (but fixed-length) units to measure this. We can use
bytes, but it's easier to use, say, number of integers used, number of fixed-sized
structures, etc. In the end, the function we come up with will be independent of
the actual number of bytes needed to represent the unit. Space complexity is
sometimes ignored because the space used is minimal and/or obvious, but
sometimes it becomes as important an issue as time.

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.

Dept. of CSE, SJBIT

Page 5

DATA STRUCTURES WITH C

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

Void add (int a[ ][MAX_SIZE] )

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

7.Estimate the space complexity of a recursive function for summing a list of


numbers. (june/jul 2014)
Soln:
float rsum(float list[ ], int n)
{
count++;
/*for if conditional */
if (n) {
count++; /* for return and rsum invocation */
return rsum(list, n-1) + list[n-1];
}
count++;
Dept. of CSE, SJBIT

Page 6

DATA STRUCTURES WITH C

10CS35

return list[0];
2n+2
Statement

s/ e

float rsum(float list[ ], int n)


{
if (n)
return rsum(list, n-1)+list[n-1];
return list[0];
}
Total

0
0
1
1
1
0

Frequency Total steps


0
0
n+1
n
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

DATA STRUCTURES WITH C

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

T(N) grows no faster than f(N)

growth rate of T(N) is less than or equal to growth rate of f(N) for large N

f(N) is an upper bound on T(N)

Omega Notation ()

Dept. of CSE, SJBIT

T(N) = (f(N)) if there are positive constants c and n0 such that


T(N) c f(N) when N n0
Page 8

DATA STRUCTURES WITH C

10CS35

T(N) grows no slower than f(N)

growth rate of T(N) is greater than or equal to growth rate of f(N) for large
N

f(N) is a lower bound on T(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

allocates the specified number of bytes

realloc

increases or decreases the size of the specified block of memory. Reallocates it


if needed

calloc

allocates the specified number of bytes and initializes them to zero

free

releases the specified block of memory back to the system

int * array = malloc(10 * sizeof(int));


int * array = calloc(10,sizeof (int));
11. Explain performance analysis and performance measurement. . (June 2013)
Soln: Performance Analysis (machine independent)
1. space complexity: storage requirement

Dept. of CSE, SJBIT

Page 9

DATA STRUCTURES WITH C

10CS35

Space Complexity:

S(P)=C+SP(I)

Fixed Space Requirements (C) Independent of the characteristics of the


inputs and outputs

instruction space

space for simple variables, fixed-size structured variable, constants

Variable Space Requirements (SP(I))


depend on the instance characteristic I

number, size, values of inputs and outputs associated with I

recursive stack space, formal parameters, local variables, return address

2. time complexity: computing time


T(P)=C+TP(I)
The time, T(P), taken by a program, P, is the sum of its compile time C
and its run (or execution) time, TP(I)
Fixed time requirements
Compile time (C), independent of instance characteristics
Variable time requirements
Run (execution) time TP
TP(n)=caADD(n)+csSUB(n)+clLDA(n)+cstSTA(n)

Performance Measurement (machine dependent)


Although performance analysis gives us a powerful tool for assessing an
algorithms space and time complexity, at some point we also must consider how
the algorithm executes on our machine.

This consideration moves us from the realm of analysis to that of


measurement.

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

DATA STRUCTURES WITH C


equal
to the sum of the sizes of its members.
3. Each member within a structure is
assigned a unique storage area.
4. Individual members can be accessed at a
time.
5. Altering the value of a member will not
affect other members of the structure.

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.

Two uses of a stucture:


Structures are used to represent more complex data structures.
An be used to pass arguments so as to minimize the number of function arguments.
Extensively used in applications involving database management.
Bit field is defined as a special type of structure or union element that allows the user to
access individual bits. Bit fields can provide greater control over the structure's storage
allocation and allow tighter packing of information in memory. Bit-fields are useful for
the following reasons:
Data can be densely packed using bit-fields.
Some devices will ransmit encoded status information in one or more bits within a byte.
Using this bitwise operators, one can see the flags that are set or reset and based on this
information, necessary action can be taken by the programmer.
Ertain encrypted routines sometimes access the bits within a byte.
Even though bit manipulations can be performed using bitwise operators, using bitfields the programs will be more structured and we can easily read and understand.
Syntax of bit-field:
struct tag
{
data_typeidentifier1 :bit_length;
data_typeidentifier2 :bit_length;
.................................
.................................
data_typeidentifier3 :bit_length;
};
where
data_type is of type int or unsigned int.
Identifier1, identifier2 etc., are the names of the bit-fields.
bit_length is the number of bits used for the identifiers.
Ex: typedefstruct
{
char name[30];
unsigned sex : 1;
unsigned age : 5;
unsignedrollno : 7;
unsigned branch : 2;
Dept. of CSE, SJBIT

Page 11

DATA STRUCTURES WITH C

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:

Dept. of CSE, SJBIT

Page 12

DATA STRUCTURES WITH C

10CS35

Fig1: representation of array


Once we've done this, we can (just as for the one-dimensional case) use array-like syntax
to access our simulated multidimensional array. If we write
array[i][j]
we're asking for the i'th pointer pointed to by array, and then for the j'thint pointed to by
that inner pointer. (This is a pretty nice result: although some completely different
machinery, involving two levels of pointer dereferencing, is going on behind the scenes,
the simulated, dynamically-allocated two-dimensional ``array'' can still be accessed just
as if it were an array of arrays, i.e. with the same pair of bracketed subscripts.). If a
program uses simulated, dynamically allocated multidimensional arrays, it becomes
possible to write ``heterogeneous'' functions which don't have to know (at compile time)
how big the ``arrays'' are. In other words, one function can operate on ``arrays'' of various
sizes and shapes. The function will look something like
func2(int **array, intnrows, intncolumns)
{
}
This function does accept a pointer-to-pointer-to-int, on the assumption that we'll only be
calling it with simulated, dynamically allocated multidimensional arrays. (We must not
call this function on arrays like the ``true'' multidimensional array a2 of the previous
sections). The function also accepts the dimensions of the arrays as parameters, so that it
will know how many ``rows'' and ``columns'' there are, so that it can iterate over them
correctly. Here is a function which zeros out a pointer-to-pointer, two-dimensional
``array'':
void zeroit(int **array, intnrows, intncolumns)
{
int i, j;
for(i = 0; i <nrows; i++)
{
for(j = 0; j <ncolumns; j++)
array[i][j] = 0;
}
}
Finally, when it comes time to free one of these dynamically allocated multidimensional
``arrays,'' we must remember to free each of the chunks of memory that we've allocated.
(Just freeing the top-level pointer, array, wouldn't cut it; if we did, all the second-level
pointers would be lost but not freed, and would waste memory.) Here's what the code
might look like:
for(i = 0; i <nrows; i++)
free(array[i]);
free(array);
3.Define a structure for the employee with the following fields: Emp_Id(integer),
Emp_Name(string), Emp_Dept(string) & Emp_age(integer) Empid, DOJ
(date,month,year) and salary (Basic, DA,HRA). Write the following functions to
process the employee data: (i) Function to read an employee record. (ii) Function to
print an employee record. (june/jul 2014) . (June 2013) (dec 2014/jan 2015)
Dept. of CSE, SJBIT

Page 13

DATA STRUCTURES WITH C

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)

Dept. of CSE, SJBIT

Page 14

DATA STRUCTURES WITH C


x

10CS35

Soln: Fast transpose


o Algorithm computes in advance the starting array index and size for each
row in the transposed matrix.
o Time complexity
O(NumberOfTerms + NumberOfColumns), which is less than
O(NumberOfRows * NumberOfColumns) for sparse matrices.
If matrix is not too sparse then NumberOfTerms is
O(NumberOfRows * NumberOfColumns), so complexity is
O(NumberOfRows * NumberOfColumns)
o Pay in space complexity due to the extra storage
A fast-transpose is a computer algorithm that quickly transposes a sparse matrix
using a relatively small amount of memory. Using arrays normally to record a
sparse matrix uses up a lot of memory since many of the matrix's values are zero.
In addition, using the normal transpose algorithm to transpose this matrix will take
O(cols*elements) amount of time. The fast-transpose algorithm only uses a little
memory to record the matrix and takes only O(cols+elements) amount of time,
which is efficient considering the number of elements equals cols*rows.

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

DATA STRUCTURES WITH C

10CS35

FILE *structin, *structout;


int i;
struct planet ss[9]; // array ss = solarsytem
if ((structin=fopen("planets.txt","r")) == NULL)
{
printf("Error: input file planets.txt cannot be opened");
system("pause");
return 1;
}
if ((structout=fopen("results.txt","w")) == NULL)
{
printf("Error: output file results.txt cannot be opened");
system("pause");
return 1;
}
for ( i = 0; i < 9; i++)
{
fscanf(structin, "%7s %lf %lf %lf", ss[i].name, &ss[i].distance, &ss[i].mass,
&ss[i].radius);
fprintf(structout, "name: %7s density: %e year: %e \n", ss[i].name, density(&ss[i]),
year(&ss[i]));
}
system("pause");
return 0;

}
// 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;
}

Dept. of CSE, SJBIT

Page 16

DATA STRUCTURES WITH C

10CS35

6. What is a polynomial ? What is the degree of the polynomial? Write a


function to add two polynomials? (dec 2013/jan 2014)
Soln: In mathematics, a polynomial (from Greek poly, "many" and medieval Latin
binomium, "binomial"[1][2][3]) is an expression of finite length constructed from variables
(also known as indeterminates) and constants, using only the operations of addition,
subtraction, multiplication, and non-negative integerexponents. For example, x2 4x + 7
is a polynomial, but x2 4/x + 7x3/2 is not, because its second term involves division by
the variable x (4/x) and because its third term contains an exponent that is not a whole
number (3/2). The term "polynomial" can also be used as an adjective, for quantities that
can be expressed as a polynomial of some parameter, as in "polynomial time" which is
used in computational complexity theory.
Polynomials appear in a wide variety of areas of mathematics and science. For example,
they are used to form polynomial equations, which encode a wide range of problems,
from elementary word problems to complicated problems in the sciences; they are used to
define polynomial functions, which appear in settings ranging from basic chemistry and
physics to economics and social science; they are used in calculus and numerical analysis
to approximate other functions. In advanced mathematics, polynomials are used to
construct polynomial rings, a central concept in abstract algebra and algebraic geometry.
A polynomial is made up of terms that are only added, subtracted or multiplied.
A polynomial looks like this:

A polynomial can have:


constants (like 3, -20, or )
variables (like x and y)
exponents (like the 2 in y2) but only 0, 1, 2, 3, ...etc
That can be combined using:
+
addition,
subtraction, and

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

DATA STRUCTURES WITH C

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

DATA STRUCTURES WITH C

10CS35

temp->link=(struct poly *) malloc(sizeof(struct poly));


temp=temp->link;
}
temp->coeff=x;
temp->exp=y;
temp->link=NULL;
}
void display(struct poly *q)
{
while(q!=NULL)
{
printf("%dx^%d",q->coeff,q->exp);
q=q->link;
}
}
void polyadd(struct poly *x,struct poly *y,struct poly **t)
{
struct poly *z;
if(x==NULL && y==NULL)
return;
while(x!=NULL && 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;
}
if(x->exp<y->exp)
{
z->coeff= y->coeff;
z->exp=y->exp;
y= y->link;
}
else if(x->exp>y->exp)
{
z->coeff=x->coeff;
z->exp=x->exp;
x=x->link;
}
else{
z->coeff=x->coeff+y->coeff;
Dept. of CSE, SJBIT

Page 19

DATA STRUCTURES WITH C

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

DATA STRUCTURES WITH C

10CS35

Enter the coeff & exp of 3 term: 1 1


2x^3
2x^2 1x^1
4x^3
3x^2 5x^1
*/

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

DATA STRUCTURES WITH C


3
5

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

DATA STRUCTURES WITH C

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

Dept. of CSE, SJBIT

Page 23

DATA STRUCTURES WITH C

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

DATA STRUCTURES WITH C

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.

Transpose of a sparse matrix.


row col value
a[0]
6 6
8
[1]
0 0
15
[2]
0 3
22
[3]
0 5 -15
[4]
1 1
11
[5]
1 2
3
[6]
2 3
-6
[7]
4 0
91
[8]
5 2
28

[1]
[2]
[3]
[5]
[6]
[7]
[8]

row col value


b[0]
6 6
8
0 0 15
0 4 91
1 1 11
[4]
2 1
3
2 5 28
3 0 22
3 2 -6
5 0 -15

(1) for each row i


take element <i, j, value> and store it
in element <j, i, value> of the transpose.
difficulty: where to put <j, i, value>?
(0, 0, 15) ====> (0, 0, 15)
(0, 3, 22) ====> (3, 0, 22)
(0, 5, -15) ====> (5, 0, -15)
(1, 1, 11) ====> (1, 1, 11)
Move elements down very often.
(2) For all elements in column j,
place element <i, j, value> in element <j, i, value>
void transpose (term a[] , term b[] )
/* b is set to the transpose of a */
{
int n, i, j, currentb;
n = a[0] .value; /* total number of elements */
b[0] .row = a[0] .col; /* rows in b = columns in a */
b[0] .col = a[0] .row; /*columns in b = rows in a */
b[0] .value = n;
if (n > 0) {
/*non zero matrix */
currentb = 1;
for (i = 0; i < a[0] .col; i++)
Dept. of CSE, SJBIT

Page 25

DATA STRUCTURES WITH C

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

DATA STRUCTURES WITH C

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

/* Representation of Polynomials using arrays */


/* Addition of two Polynomials */
#include <stdio.h>
#define MAX 10
int main(){
int poly1[MAX]={0},poly2[MAX]={0},poly3[MAX]={0};
int i,deg1,deg2,deg3;
printf(nEnter degree of first polynomial?);
scanf(%d,&deg1);
printf(nEnter degree of second polynomial?);
scanf(%d,&deg2);
printf(nFor first polynomial:);
for(i=0;i<deg1;i++){
printf(nEnter Coefficient for Exponent %d> ,i);
scanf(%d,&poly1[i]);
}
printf(nFor second polynomial:);
for(i=0;i<deg2;i++){
Dept. of CSE, SJBIT

Page 27

DATA STRUCTURES WITH C

10CS35

printf(nEnter Coefficient for Exponent %d> ,i);


scanf(%d,&poly2[i]);
}
printf(nGenerating sum!);
printf(nPress any key to continue);
deg3 = (deg1>deg2)?deg1:deg2;
for(i=0;i<deg3;i++)
poly3[i] = poly1[i] + poly2[i];
printf(nnAddition Result:nn);
for(i=deg1-1;i>=0;i)
printf((%dx^%d)+,poly1[i],i);
printf(b n);
for(i=deg2-1;i>=0;i)
printf((%dx^%d)+,poly2[i],i);
printf(b n);
for(i=deg3-1;i>=0;i)
printf((%dx^%d)+,poly3[i],i);
printf(b n);
}

Dept. of CSE, SJBIT

Page 28

DATA STRUCTURES WITH C

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:

Algorithm to convert from infix to postfix:


As long as the precedence value of the symbol on top of the stack is greater than the
precedence value of the current input symbol, poop an item from the stack and place it in
the postfix expression. The code for this statement can be of the form:
while(F(s[top]) > G(symbol))
{
postfix[j++] = s[top];
}
Once the condition in the while loop is failed, if the precedence of the symbol on top of
the stack is not equal to the precedence value of the current input symbol, push the
current symbol on to the stack. Otherwise, delete an item from the stack but do not place
it in the postfix expression. The code for this statement can be of the form :
if(F(s[top]) != G(symbol))
s[++top] = symbol;
else
top--;
These 2 steps have to be performed for each input symbol in the infix expression.
AB+C-BA+C$- A=1 B=2 C=3.
=12+321+3$Dept. of CSE, SJBIT

Page 29

DATA STRUCTURES WITH C

10CS35

Required result = -27


2. What is the advantage of circular queue over ordinary queue? Mention any 2
applications of queues. Write an algorithm CQINSERT for static implementation of
circular queue. (june/jul 2014) (dec 2013/jan 2014) (june/july 2013)
Soln:
Advantages of circular queue over ordinary queue: Rear insertion is denied in an
ordinary queue even if room is available at the front end. Thus, even if free memory is
available, we cannot access these memory locations. This is the major disadvantage of
linear queues.
In circular queue, the elements of a given queue can be stored efficiently in an array so
as to wrap around so that end of the queue is followed by the front of queue.
This circular representation allows the entire array to store the elements without shifting
any data within the queue.
Applications of queues:
Queues are useful in time sharing systems where many user jobs will be waiting in the
system queue for processing. These jobs may request the services of the CPU, main
memory or external devices such as printer etc. All these jobs will be given a fixed time
for processing and are allowed to use one after the other. This is the case of an ordinary
Dept. of CSE, SJBIT

Page 30

DATA STRUCTURES WITH C

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);

Dept. of CSE, SJBIT

Page 31

DATA STRUCTURES WITH C

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

DATA STRUCTURES WITH C

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

DATA STRUCTURES WITH C

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

DATA STRUCTURES WITH C

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

Dept. of CSE, SJBIT

Page 35

DATA STRUCTURES WITH C

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.

Create a new node in memory, set its data to val


h Make the node point to itself
hif tail is empty, then return this node, its the only one in the list
hIf its not the only node, then its next is tail ->next
hand tail - >next should now point to the new node.
typedef
struct
node {
int
data;
node *next;
} node;
node* AddFront(node* tail, int val)
{
// Create the new node
node *temp = (node*)malloc(sizeof(node));
temp->data = val;
// Set the new nodes next to itself (circular!)
temp->next = temp;
// If the list is empty, return new node
if (tail == NULL) return temp;
// Set our new nodes next to the front
temp->next = tail->next;
// Set tails next to our new node
tail->next = temp;
// Return the end of the list
return tail;
}
Struct node* AddEnd(struct node* tail, int val)
{
// Create the new node
node *temp = (node*)
malloc ( sizeof(node));
temp->data = val;
// Set the new nodes next to itself (circular!)
temp->next = temp;
// If the list is empty, return new node
Dept. of CSE, SJBIT

Page 36

DATA STRUCTURES WITH C

10CS35

if (tail == NULL) return temp;


// Set our new nodes next to the front
temp->next = tail->next;
// Set tails next to our new node
tail->next = temp;
// Return the
new end of the list
return temp;
}
4. Write the following functions for singly linked list: i) Reverse the list
ii)Concatenate two lists. (june/jul 2014) (june/jul 2015)
Soln:
Another useful subroutine is one which concatenates two chains X and Y.
procedure CONCATENATE(X, Y, Z)
//X = (a1, ...,am), Y = (b1, ...,bn), m,n 0, produces a new chain
Z = (a1, ...,am,b1 , ...,bn)//
Z X
if X = 0 then [Z Y; return]
if Y = 0 then return
p X
while LINK(p) 0 do
//find last node of X//
p LINK(p)
end
LINK(p) Y
//link last node of X to Y//
end CONCATENATE
This algorithm is also linear in the length of the first list. From an aesthetic point of view
it is nicer to write this procedure using the case statement in SPARKS. This would look
like:
procedure CONCATENATE(X, Y, Z)
case
: X = 0 :Z Y
:Y=0:Z X
: else : p X; Z X
while LINK(p) 0 do
p LINK (p)
end
LINK(p) Y
end
end CONCATENATE

Dept. of CSE, SJBIT

Page 37

DATA STRUCTURES WITH C

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.

Dept. of CSE, SJBIT

Page 38

DATA STRUCTURES WITH C

10CS35

PART B
Unit 5
TREES 1

1. Define the tree & the following:


i) Binary tree
ii) Complete binary tree
iii) Almost complete binary tree
iv) Binary search tree
v) Depth of a tree
vi) Degree of a binary tree
vii) Level of a binary tree
viii) Sibling
ix) Root node
x) Child
xi) Ancestors (Dec 2014/Jan 2015) (june/jul 2014) (dec 2013/jan 2014) (June 2013)
Soln: i)Binary tree A binary tree is a tree which is a collection of zero or more nodes
and
finite set of directed lines called branches that connect the nodes. A tree can be empty
or partitioned into three subgroups, namely :
* Root If tree is not empty, the first node is called root node.
* Left subtree It is a tree which is connected to the left of root.
* Right subtree - It is a tree which is connected to the right of root.

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

DATA STRUCTURES WITH C

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:

The depth of the tree = 2


vi) Degree of a binary tree
vii) Level of a binary tree
viii) Sibling
Dept. of CSE, SJBIT

Page 40

DATA STRUCTURES WITH C

10CS35

ix) Root node


x) Child
xi) Ancestors

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:

EX: Left in-threaded binary tree:

Dept. of CSE, SJBIT

Page 41

DATA STRUCTURES WITH C

10CS35

Advantages of TBT over binary tree:

3. Write c function for the following tree traversals: i)inorder ii)preorder


iii)postorder & apply for the expression A/B-C*D+E and give the result. (june/july
2013) (June 2013)
Soln: Preorder

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

DATA STRUCTURES WITH C

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

Dept. of CSE, SJBIT

Page 43

DATA STRUCTURES WITH C

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

3. Insert the new element to the vacant node

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

DATA STRUCTURES WITH C


v.

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

DATA STRUCTURES WITH C

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

DATA STRUCTURES WITH C

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

DATA STRUCTURES WITH C

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

DATA STRUCTURES WITH C

10CS35

element has a priority or value. The operations performed on a double-ended priority


queue are:
1.
2.
3.
4.
5.
6.

isEmpty() ... return true iff the DEPQ is empty


size() ... return the number of elements in the DEPQ
getMin() ... return element with minimum priority
getMax() ... return element with maximum priority
put(x) ... insert the element x into the DEPQ
removeMin() ... remove an element with minimum priority and return this
element
7. removeMax() ... remove an element with maximum priority and return this
element
Application to External Sorting
The internal sorting method that has the best expected run time is quick sort (see Section
19.2.3). The basic idea in quick sort is to partition the elements to be sorted into three
groups L, M, and R. The middle group M contains a single element called the pivot, all
elements in the left group L are <= the pivot, and all elements in the right group R are>=
the pivot. Following this partitioning, the left and right element groups are sorted
recursively.
In an external sort, we have more elements than can be held in the memory of our
computer. The elements to be sorted are initially on a disk and the sorted sequence is to
be left on the disk. When the internal quick sort method outlined above is extended to an
external quick sort, the middle group M is made as large as possible through the use of a
DEPQ. The external quick sort strategy is:
1. Read in as many elements as will fit into an internal DEPQ. The elements in the
DEPQ will eventually be the middle group of elements.
2. Read in the remaining elements. If the next element is <= the smallest element in
the DEPQ, output this next element as part of the left group. If the next element is
>= the largest element in the DEPQ, output this next element as part of the right
group. Otherwise, remove either the max or min element from the DEPQ (the
choice may be made randomly or alternately); if the max element is removed,
output it as part of the right group; otherwise, output the removed element as part
of the left group; insert the newly input element into the DEPQ.
3. Output the elements in the DEPQ, in sorted order, as the middle group.
4. Sort the left and right groups recursively.
Generic Methods for DEPQs:
General methods exist to arrive at efficient DEPQ data structures from single-ended
priority queue (PQ) data structures that also provide an efficient implementation of the
remove(theNode) operation (this operation removes the node theNode from the PQ). The
simplest of these methods, dual structure method, maintains both a min PQ and a max
PQ of all the DEPQ elements together with correspondence pointers between the nodes
Dept. of CSE, SJBIT

Page 49

DATA STRUCTURES WITH C

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.

Figure 1 Dual heap


Although the figure shows each element stored in both the min and the max heap, it is
necessary to store each element in only one of the two heaps.
The isEmpty and size operations are implemented by using a variable size that keeps
track of the number of elements in the DEPQ. The minimum element is at the root of the
min heap and the maximum element is at the root of the max heap. To insert an element
x, we insert x into both the min and the max heaps and then set up correspondence
pointers between the locations of x in the min and max heaps. To remove the minimum
element, we do a removeMin from the min heap and a remove(theNode), where theNode
is the corresponding node for the removed element, from the max heap. The maximum
element
is
removed
in
an
analogous
way.
Total and leaf correspondence are more sophisticated correspondence methods. In both
of these, half the elements are in the min PQ and the other half in the max PQ. When the
number of elements is odd, one element is retained in a buffer. This buffered element is
not in either PQ. In total correspondence, each element a in the min PQ is paired with a
distinct element b of the max PQ. (a,b) is a corresponding pair of elements such that
priority(a) <= priority(b). Figure 2 shows a total correspondence heap for the 11 elements
2, 3, 4, 4, 5, 5, 6, 7, 8, 9, 10. The element 9 is in the buffer. Corresponding pairs are
shown by red arrows.

Figure 2 Total correspondence heap


In leaf correspondence, each leaf element of the min and max PQ is required to be part of
a corresponding pair. Nonleaf elements need not be in any corresponding pair. Figure 3
shows a leaf correspondence heap.

Dept. of CSE, SJBIT

Page 50

DATA STRUCTURES WITH C

10CS35

Figure 3 A leaf correspondence heap


Total and leaf correspondence structures require less space than do dual structures.
However, the DEPQ algorithms for total and leaf correspondence structures are more
complex than those for dual structures. Of the three correspondence types, leaf
correspondence generally results in the fastest DEPQ correspondence structures.
Using any of the described correspondence methods, we can arrive at DEPQ structures
from heaps, height biased leftist trees, and pairing heaps. In these DEQP structures, the
operations put(x), removeMin(), and removeMax() take O(log n) time (n is the number of
elements in the DEPQ, for pairing heaps, this is an amortized complexity), and the
remaining
DEPQ
operations
take
O(1)
time.
4. Define the following : i) Leftist trees ii) Min leftist trees iii) Weighted leftist trees.
(june/jul 2014) (june/july 2013) (June 2013) June 2015)
Soln: i) An external node is an imaginary node in a location of a missing child.

Notation. Let the s-value of a node be the shortest distance from the node to an external
node.

x
x

An external node has the s-value of 0.


An internal node has the s-value of 1 plus the minimum of the s-values of its
internal and external children.

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

DATA STRUCTURES WITH C

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

Dept. of CSE, SJBIT

Page 52

DATA STRUCTURES WITH C

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

The root is colored black


All the paths from the root to the leaves agree on the number of black nodes
No path from the root to a leaf may contain two consecutive nodes colored red

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

DATA STRUCTURES WITH C


Zig-zag:

Zig-zig:

\
x
z
/

/
x

====> x ====>
/
y z
y
x
y
\
====> / \ ====>
x z
\
z

Dept. of CSE, SJBIT

10CS35
/\

Page 54

You might also like