data structures with c - atria | e-learning | … structures with c 10cs35 dept of cse,sjbit 7 unit...

66
DATA STRUCTURES WITH C Subject Code: 10CS35 QUESTION BANK SOLUTION

Upload: lytuyen

Post on 13-Apr-2018

214 views

Category:

Documents


2 download

TRANSCRIPT

DATA STRUCTURES WITH C

Subject Code: 10CS35

QUESTION BANK SOLUTION

Data Structures with C 10CS35

Dept of CSE,SJBIT 2

UNIT 1

BASIC CONCEPTS

1. What is a Pointer.Can we have multiple pointer to a variable? Explain Lvalue andRvalue expression. (10m)(June / July11),(dec 2010), (may/jun 2010)A pointer is a variable whose value is the address of another variable ie. direct address of thememory location. Like any variable or constant, you must declare a pointer before you can use itto store any variable address. The general form of a pointer variable declaration is:type *var-name;Here, type is the pointer's base type; it must be a valid C data type and var-name is the name ofthe pointer variable. The asterisk * you used to declare a pointer is the same asterisk that you usefor multiplication. However, in this statement the asterisk is being used to designate a variable asa pointer. Following are the valid pointer declaration:int *ip; /* pointer to an integer */double *dp; /* pointer to a double */float *fp; /* pointer to a float */char *ch /* pointer to a character */The actual data type of the value of all pointers, whether integer, float, character, or otherwise, isthe same, a long hexadecimal number that represents a memory address. The only differencebetween pointers of different data types is the data type of the variable or constant that thepointer points to.

How to use Pointers?There are few important operations which we will do with the help of pointers very frequently.(a) we define a pointer variables (b) assign the address of a variable to a pointer and (c) finallyaccess the value at the address available in the pointer variable. This is done by using unaryoperator * that returns the value of the variable located at the address specified by its operand.Following example makes use of these operations:

#include <stdio.h>

int main (){

int var = 20; /* actual variable declaration */int *ip; /* pointer variable declaration */

ip = &var; /* store address of var in pointer variable*/

printf("Address of var variable: %x\n", &var );

/* address stored in pointer variable */

Data Structures with C 10CS35

Dept of CSE,SJBIT 3

printf("Address stored in ip variable: %x\n", ip );

/* access the value using the pointer */printf("Value of *ip variable: %d\n", *ip );

return 0;}Expressions that refer to memory locations are called "l-value" expressions. An l-valuerepresents a storage region's "locator" value, or a "left" value, implying that it can appear on theleft of the equal sign (=). L-values are often identifiers.Expressions referring to modifiable locations are called "modifiable l-values." A modifiable l-value cannot have an array type, an incomplete type, or a type with the const attribute. Forstructures and unions to be modifiable l-values, they must not have any members with the constattribute. The name of the identifier denotes a storage location, while the value of the variable isthe value stored at that location.An identifier is a modifiable l-value if it refers to a memory location and if its type is arithmetic,structure, union, or pointer. For example, if ptr is a pointer to a storage region, then *ptr is amodifiable l-value that designates the storage region to which ptr points.Any of the following C expressions can be l-value expressions:An identifier of integral, floating, pointer, structure, or union typeA subscript ([ ]) expression that does not evaluate to an arrayA member-selection expression (–> or .)A unary-indirection (*) expression that does not refer to an arrayAn l-value expression in parenthesesA const object (a nonmodifiable l-value)The term "r-value" is sometimes used to describe the value of an expression and to distinguishit from an l-value. All l-values are r-values but not all r-values are l-values.

2. Give atleast 2 differences between : i. Static memory allocation and dynamicmemory allocation.ii. Malloc() and calloc().(10m)(June / July11), (dec 2010)

Static memory allocation Dynamic memory allocation

1.Memory is allocated during compilation time. 1. Memory is allocated during execution time.

2. Used only when the data size is fixedand known in advance before processing.

2. Used only for unpredictable memoryrequirement.

malloc() calloc()

Data Structures with C 10CS35

Dept of CSE,SJBIT 4

1.The syntax of malloc() is:ptr = (data_type*)malloc(size);The required number of bytes to beallocated is specified as argument i.e.,size in bytes.

1.The syntax of calloc() is:ptr = (data_type*)calloc(n,size);takes 2 arguments – n number of blocksto be allocated and size is number ofbytes to be allocated for each block.

2. Allocated space will not be initialized. 2. Each byte of allocated space is initialized tozero.

3. Write a C program using pass by reference method to swap 2 characters.ii) Giveany 2 advantages and disadvantages of using pointers.(20m)( dec 2011)SWAPPING://This program swaps the values in the variable using function containing reference arguments#include<iostream.h>void swap(int &iNum1, int &iNum2);void main(){int iVar1, iVar2;cout<<"Enter two numbers "<<endl;cin>>iVar1;cin>>iVar2;swap(iVar1, iVar2);cout<<"In main "<<iVar1<<" "<<iVar2<<endl;}

void swap(int &iNum1, int &iNum2){int iTemp;iTemp = iNum1;iNum1 = iNum2;iNum2 = iTemp;cout<<"In swap "<<iNum1<<" "<<iNum2<<endl;}The main advantages of using pointers are1.) Function cannot return more than one value. But when the same function can modify manypointer variables and function as if it is returning more than one variable.2.) In the case of arrays, we can decide the size of th array at runtime by allocating the necessaryspace.3.) In the case of pointers to classes, we can use polymorphism and virtual classes to change thebehavior of pointers to various types of classes at runtime

The disadvantages of pointers

Data Structures with C 10CS35

Dept of CSE,SJBIT 5

1.) If sufficient memory is not available during runtime for the storage of pointers, the programmay crash (least possible)2.) If the programmer is not careful and consistent with the use of pointers, the program maycrash (very possible)A brief synopsis on the "rules" of pointers1.) Always initialize a pointer by calling an allocator2.) Alway check to see if the allocation request failed3.) Always deallocate memory controlled by a pointer when done with it4.) Never access memory that has not been allocated - pay attention to the size of arrays5.) Never access memory that has been deallocated6.) Do not allocate and deallocate memory with wild abandon, because that can fragment thevirtual memory address space, causing future allocation requests to fail - particularly in longrunning programs such as web servers4. What is an algorithm? Briefly explain the criteria that an algorithm mustsatisfy.(10m)(dec 2012)An algorithm is an effective method expressed as a finite list of well-defined instructionsforcalculating a function Starting from an initial state and initial input (perhaps empty) theinstructions describe a computation that, when executed, proceeds through a finite number of

well-defined successive states, eventually producing "output" and terminating at a final endingstate. The transition from one state to the next is not necessarily deterministic; some algorithms,known as randomized algorithms, incorporate random input.specifications. AL provides an independent, portable description which can be related to different proofsystems and different programming languages. Several interfaces have been explored and tools for fullyautomatic translation of AL specifications into the HOL logic and Standard ML executable codehave been implemented. A substantial case study uses AL as the common specification language from

Data Structures with C 10CS35

Dept of CSE,SJBIT 6

which both the formal proofs of correctness and executable code have been produced.

5. Write a recursive function to implement binary search.(10m)(dec 2012)#include <stdio.h>binarysearch(int a[],int n,int low,int high){ int mid;if (low > high)return -1;mid = (low + high)/2;if(n == a[mid]){ printf(“The element is at position %d\n”,mid+1);return 0;}if(n < a[mid]){ high = mid – 1;binarysearch(a,n,low,high);}if(n > a[mid]){ low = mid + 1;binarysearch(a,n,low,high);}}

main(){ int a[50];int n,no,x,result;printf(“Enter the number of terms : “);scanf(“%d”,&no);printf(“Enter the elements :\n”);for(x=0;x&ltno;x++)scanf(“%d”,&a[x]);printf(“Enter the number to be searched : “);scanf(“%d”,&n);result = binarysearch(a,n,0,no-1);if(result == -1)printf(“Element not found”);return 0;}

Data Structures with C 10CS35

Dept of CSE,SJBIT 7

UNIT 2

ARRAYS and STRUCTURES

1. How does a structure differ from an union? Mention any 2 uses of structure. Whatis a bit field? Why are bit fields used with structures? (12M)(June / July10),(dec 2010),(may/jun 2011)

A structure type is usually defined near to the start of a file using a typedef statement. typedefdefines and names a new type, allowing its use throughout the program. typedefs usually occurjust after the #define and #include statements in a file.

Here is an example structure definition.

typedef struct {

Data Structures with C 10CS35

Dept of CSE,SJBIT 8

char name[64];char course[128];int age;int year;

} student;

This defines a new type student variables of type student can be declared as follows.

student st_rec;Notice how similar this is to declaring an int or float.

The variable name is st_rec, it has members called name, course, age and year.

2. Explain dynamic allocating an array with an example. (6m)(Jun-June 10)First you have to create an array of char pointers, one for each string (char *):

char **array = (char **)malloc(totalstrings * sizeof(char *));

Next you need to allocate space for each string:

int i;for (i = 0; i < totalstrings; ++i) {

array[i] = (char *)malloc(stringsize+1);}When you're done using the array, you must remember to free() each of the pointers you'veallocated. That is, loop through the array calling free() on each of its elements, and thenfree(array) as well.

Data Structures with C 10CS35

Dept of CSE,SJBIT 9

3. Differntiate structures and unions. WAP to store student details using structures.(12m)(Dec-Jan11)

4. WAP to bubble sort a given array. (8m)(Dec-Jan11).

#include <stdio.h>

int main(){

int array[100], n, c, d, swap;

printf("Enter number of elements\n");scanf("%d", &n);

printf("Enter %d integers\n", n);

for (c = 0; c < n; c++)scanf("%d", &array[c]);

for (c = 0 ; c < ( n - 1 ); c++){

for (d = 0 ; d < n - c - 1; d++){

Data Structures with C 10CS35

Dept of CSE,SJBIT 10

if (array[d] > array[d+1]) /* For decreasing order use < */{

swap = array[d];array[d] = array[d+1];array[d+1] = swap;

}}

}

printf("Sorted list in ascending order:\n");

for ( c = 0 ; c < n ; c++ )printf("%d\n", array[c]);

return 0;}5. Explain multidimensional arrays with an example to multiply two matrices.(12m)(Dec-Jan-12)For a two-dimensional array, the element with indices i,j would have address B + c · i + d · j,where the coefficients c and d are the row and column address increments, respectively.More generally, in a k-dimensional array, the address of an element with indices i1, i2, …, ik isB + c1 · i1 + c2 · i2 + … + ck · ik.For example: int a[3][2];This means that array a has 3 rows and 2 columns, and the array is of integer type. Here we canstore 6 elements they are stored linearly but starting from first row linear then continuing withsecond row. The above array will be stored as a11, a12, a13, a21, a22, a23.This formula requires only k multiplications and k additions, for any array that can fit inmemory. Moreover, if any coefficient is a fixed power of 2, the multiplication can be replaced bybit shifting.The coefficients ck must be chosen so that every valid index tuple maps to the address of adistinct element.If the minimum legal value for every index is 0, then B is the address of the element whoseindices are all zero. As in the one-dimensional case, the element indices may be changed bychanging the base address B. Thus, if a two-dimensional array has rows and columns indexedfrom 1 to 10 and 1 to 20, respectively, then replacing B by B + c1 - − 3 c1 will cause them to berenumbered from 0 through 9 and 4 through 23, respectively. Taking advantage of this feature,some languages (like FORTRAN 77) specify that array indices begin at 1, as in mathematicaltradition; while other languages (like Fortran 90, Pascal and Algol) let the user choose theminimum value for each index.Dope vectors[edit]The addressing formula is completely defined by the dimension d, the base address B, and theincrements c1, c2, …, ck. It is often useful to pack these parameters into a record called the

Data Structures with C 10CS35

Dept of CSE,SJBIT 11

array's descriptor or stride vector or dope vector.[2][3] The size of each element, and theminimum and maximum values allowed for each index may also be included in the dope vector.The dope vector is a complete handle for the array, and is a convenient way to pass arrays asarguments to procedures. Many useful array slicing operations (such as selecting a sub-array,swapping indices, or reversing the direction of the indices) can be performed very efficiently bymanipulating the dope vector.[2]Compact layouts[edit]Often the coefficients are chosen so that the elements occupy a contiguous area of memory.However, that is not necessary. Even if arrays are always created with contiguous elements,some array slicing operations may create non-contiguous sub-arrays from them.There are two systematic compact layouts for a two-dimensional array. For example, considerthe matrix

In the row-major order layout (adopted by C for statically declared arrays), the elements in eachrow are stored in consecutive positions and all of the elements of a row have a lower addressthan any of the elements of a consecutive row:1 2 3 4 5 6 7 8 9In column-major order (traditionally used by Fortran), the elements in each column areconsecutive in memory and all of the elements of a column have a lower address than any of theelements of a consecutive column:1 4 7 2 5 8 3 6 9For arrays with three or more indices, "row major order" puts in consecutive positions any twoelements whose index tuples differ only by one in the last index. "Column major order" isanalogous with respect to the first index.In systems which use processor cache or virtual memory, scanning an array is much faster ifsuccessive elements are stored in consecutive positions in memory, rather than sparselyscattered. Many algorithms that use multidimensional arrays will scan them in a predictableorder. A programmer (or a sophisticated compiler) may use this information to choose betweenrow- or column-major layout for each array. For example, when computing the product A·B oftwo matrices, it would be best to have A stored in row-major order, and B in column-majororder.#include <stdio.h>

int main(){

int m, n, p, q, c, d, k, sum = 0;int first[10][10], second[10][10], multiply[10][10];

printf("Enter the number of rows and columns of first matrix\n");scanf("%d%d", &m, &n);printf("Enter the elements of first matrix\n");

Data Structures with C 10CS35

Dept of CSE,SJBIT 12

for ( c = 0 ; c < m ; c++ )for ( d = 0 ; d < n ; d++ )

scanf("%d", &first[c][d]);

printf("Enter the number of rows and columns of second matrix\n");scanf("%d%d", &p, &q);

if ( n != p )printf("Matrices with entered orders can't be multiplied with each other.\n");

else{

printf("Enter the elements of second matrix\n");

for ( c = 0 ; c < p ; c++ )for ( d = 0 ; d < q ; d++ )

scanf("%d", &second[c][d]);

for ( c = 0 ; c < m ; c++ ){

for ( d = 0 ; d < q ; d++ ){

for ( k = 0 ; k < p ; k++ ){

sum = sum + first[c][k]*second[k][d];}

multiply[c][d] = sum;sum = 0;

}}

printf("Product of entered matrices:-\n");

for ( c = 0 ; c < m ; c++ ){

for ( d = 0 ; d < q ; d++ )printf("%d\t", multiply[c][d]);

printf("\n");}

}

Data Structures with C 10CS35

Dept of CSE,SJBIT 13

return 0;}6. WAP to implement Sparse matrix.(8m)(Dec-Jan-12)#include<stdio.h>#include<conio.h>

int spa[10][10];void spmatrix(int,int,int);void main(){ int i,j,n,m,num,elem=0;

clrscr();printf("\nenter no. of rows: ");scanf("%d",&n);printf("\nenter no. of column: ");scanf("%d",&m);printf("\nenter the elements of array\n");for(i=0;i<n;i++){ for(j=0;j<m;j++)

{ scanf("%d",&spa[i][j]);}

}printf("\nmatrix:\n");for(i=0;i<n;i++){for(j=0;j<m;j++){ printf(" %d",spa[i][j]);}printf("\n");

}

for(i=0;i<n;i++){ for(j=0;j<m;j++)

{ if(spa[i][j]!=0)elem++;

}}spmatrix(elem+1,n,m);

getch();}

void spmatrix(int t,int n,int m){ int b[10][3],i,j,q=1;

b[0][0]=n;

Data Structures with C 10CS35

Dept of CSE,SJBIT 14

b[0][1]=m;b[0][2]=t-1;for(i=1;i<=n;i++){for(j=1;j<=m;j++){ if(spa[i-1][j-1]!=0)

{ b[q][0]=i;b[q][1]=j;b[q][2]=spa[i-1][j-1];

q++;}}

}printf("\n\nsparse matrix:\n");for(i=0;i<t;i++){for(j=0;j<3;j++){ printf(" %d",b[i][j]);}printf("\n");

}}

Data Structures with C 10CS35

Dept of CSE,SJBIT 15

UNIT 3STACKS AND QUEUES

1. How do you define a data structure? How is stack a data structure? Give a Cprogram to construct a stack of integers and perform all the necessary operations on it.(10m)(June / July11), (dec 2011), (dec 2010), (may/jun 2010), (dec/jan12)Data structures are generally based on the ability of a computer to fetch and store data at anyplace in its memory, specified by an address—a bit string that can be itself stored in memory andmanipulated by the program. Thus the record and array data structures are based on computingthe addresses of data items witharithmetic operations; while the linked data structures are basedon storing addresses of data items within the structure itself. Many data structures use bothprinciples, sometimes combined in non-trivial ways (as in XOR linking).The implementation of a data structure usually requires writing a set of procedures that createand manipulate instances of that structure. The efficiency of a data structure cannot be analyzedseparately from those operations. This observation motivates the theoretical concept ofan abstract data type, a data structure that is defined indirectly by the operations that may beperformed on it, and the mathematical properties of those operations (including their space andtime cost).The array implementation aims to create an array where the first element (usually at the zero-offset) is the bottom. That is, array[0] is the first element pushed onto the stack and the lastelement popped off. The program must keep track of the size, or the length of the stack. Thestack itself can therefore be effectively implemented as a two-element structure in C:typedef struct {

size_t size;int items[STACKSIZE];

} STACK;The push() operation is used both to initialize the stack, and to store values to it. It is responsiblefor inserting (copying) the value into the ps->items[] array and for incrementing the elementcounter (ps->size). In a responsible C implementation, it is also necessary to check whether thearray is already full to prevent an overrun.void push(STACK *ps, int x){

if (ps->size == STACKSIZE) {fputs("Error: stack overflow\n", stderr);abort();

} elseps->items[ps->size++] = x;

}The pop() operation is responsible for removing a value from the stack, and decrementing thevalue of ps->size. A responsible C implementation will also need to check that the array is notalready empty.int pop(STACK *ps){

Data Structures with C 10CS35

Dept of CSE,SJBIT 16

if (ps->size == 0){fputs("Error: stack underflow\n", stderr);abort();

} elsereturn ps->items[--ps->size];

}If we use a dynamic array, then we can implement a stack that can grow or shrink as much asneeded. The size of the stack is simply the size of the dynamic array. A dynamic array is a veryefficient implementation of a stack, since adding items to or removing items from the end of a

dynamic array is amortized O(1) time.PROGRAM#include<stdio.h>#include<stdlib.h>

#define MAX_SIZE 5

int stack[MAX_SIZE];void push();int pop();void traverse();int is_empty();int top_element();int top = -1;

main(){

int element, choice;

while(1){

Data Structures with C 10CS35

Dept of CSE,SJBIT 17

printf("Stack Operations.\n");printf("1. Insert into stack (Push operation).\n");printf("2. Delete from stack (Pop operation).\n");printf("3. Print top element of stack.\n");printf("4. Check if stack is empty.\n");printf("5. Traverse stack.\n");printf("6. Exit.\n");printf("Enter your choice.\n");scanf("%d",&choice);

switch ( choice ){

case 1:if ( top == MAX_SIZE - 1 )

printf("Error: Overflow\n\n");else{

printf("Enter the value to insert.\n");scanf("%d",&element);push(element);

}break;

case 2:if ( top == -1 )

printf("Error: Underflow.\n\n");else{

element = pop();printf("Element removed from stack is %d.\n", element);

}break;

case 3:if(!is_empty()){

element = top_element();printf("Element at the top of stack is %d\n\n", element);

}else

printf("Stack is empty.\n\n");break;

Data Structures with C 10CS35

Dept of CSE,SJBIT 18

case 4:if(is_empty())

printf("Stack is empty.\n\n");else

printf("Stack is not empty.\n\n");break;

case 5:traverse();break;

case 6:exit(0);

}}

}

void push(int value){

top++;stack[top] = value;

}

int pop(){

int element;

if ( top == -1 )return top;

element = stack[top];top--;

return element;}

void traverse(){

int d;

if ( top == - 1 )

Data Structures with C 10CS35

Dept of CSE,SJBIT 19

{printf("Stack is empty.\n\n");return;

}

printf("There are %d elements in stack.\n", top+1);

for ( d = top ; d >= 0 ; d-- )printf("%d\n", stack[d]);

printf("\n");}

int is_empty(){

if ( top == - 1 )return 1;

elsereturn 0;

}

int top_element(){

return stack[top];}2. Write an algorithm to convert a valid infix expression to a postfix expression. Alsoevaluate the following suffix expression for the values: A=1 B=2 C=3. AB+C-BA+C$-(10m)(Jun-Jul11)(Dec-Jan12).The algorithm transforms the infix expression A into equivalent postfix B. The algorithm usesstack to temporirly hold opertors and left parenthesis. The postfix expression B will beconstructed left to right using operands from A and operators which are removed from STACK.We begin by pushing left parenthesis onto STACK and adding a right parenthesis at the end ofA. The algorithm is finished when STACK is empty.

Step 1. Push Left Parenthesis “(“ onto stack and add right parenthesis “)” to end of the AStep 2. Scan A from left to right and repeat steps 3 to 6 for each element of A until the stack isemptyStep 3. If an operand is encountered, add it to BStep 4. If a left parenthesis is encountered push it onto the stackStep 5. If an operator is encountered thena. Repeatedly pop from the STACK and add to B each operator (on the top of the stack) whichhas the same precedence as or higher precedence than operatorb. Add operator to STACK

Data Structures with C 10CS35

Dept of CSE,SJBIT 20

Step 6. If a right parenthesis is encountered, thena. Repeatedly pop from the STACK and add to B each operator (on the top of STACK) until aleft parenthesis is encounteredb. Remove the left parenthesis. (Do not add left parenthesis to B)Step 7. Exit

For, example consider the following arithmetic infix expressionA =A+(B*C-(D/E^F)*G)*H)A + ( B * C - ( D / E ^ F

) * G ) * H )1 2 3 4 5 6 7 8 9 10 11 12 13

14 15 16 17 18 19 20The elements of A have now been labelled from left to right for easy reference. The table belowshows the status of STACK and of the Postfix string B as each element of A is scanned.1. Each element is simply added to B and does not chang STACK2. The subtraction operator (-) in row 7 sends * from STACK to P before it (-) is pushed onto thestack.3. The right parenthesis in row 14 sends ^ and then / from STACK to B, and then removes theleft parenthesis from the STACK.4. The right parenthesis in row 20 sends * then + from STACK to B and then removes the leftparenthesis from top of the STACK.After step 20 is executed, the stack is empty.

3. WAP to evaluate a postfix expression.(10m)(Jun-jul-10)

#include<stdio.h>

#include<conio.h>

float stack[10];

int top=-1;

void push(char);

float pop();

float eval(char [],float[]);

void main()

{

int i=0;

char suffix[20];

float value[20],result;

clrscr();

printf("Enter a valid postfix expression\t");

Data Structures with C 10CS35

Dept of CSE,SJBIT 21

gets(suffix);

while (suffix[i]!='\0')

{

if(isalpha(suffix[i]))

{

fflush(stdin);

printf("\nEnter the value of %c",suffix[i]);

scanf("%f",&value[i]);

}

i++;

}

result=eval(suffix,value);

printf("The result of %s=%f",suffix,result);

getch();

}

float eval(char suffix[],float data[])

{

int i=0;

float op1,op2,res;

char ch;

while(suffix[i]!='\0')

{

ch=suffix[i];

if(isalpha(suffix[i]))

{

push(data[i]);

}

else

{

op2=pop();

op1=pop();

switch(ch)

{

case '+' : push(op1+op2);

break;

case '-' : push(op1-op2);

break;

case '*' : push(op1+op2);

Data Structures with C 10CS35

Dept of CSE,SJBIT 22

break;

case '/' :push(op1/op2);

break;

case '^' : push(pow(op1,op2));

break;

}

}

i++;

}

res=pop();

return(res);

}

void push(char num)

{

top=top+1;

stack[top]=num;

}

float pop()

{

float num;

num=stack[top];

top=top-1;

return(num);

}

4. What is a queue. Explain its imlplementation.WAP to QINSERT and QDELETE.(10m)(Dec-Jan10)A queue (/ˈkjuː/ kew) is a particular kind of abstract data type or collection in which the entitiesin the collection are kept in order and the principal (or only) operations on the collection are theaddition of entities to the rear terminal position, known as enqueue, and removal of entities fromthe front terminal position, known as dequeue. This makes the queue a First-In-First-Out (FIFO)data structure. In a FIFO data structure, the first element added to the queue will be the first oneto be removed. This is equivalent to the requirement that once a new element is added, allelements that were added before have to be removed before the new element can be removed.Often a peek or front operation is also implemented, returning the value of the front elementwithout dequeuing it. A queue is an example of a linear data structure, or more abstractly asequential collection.

Data Structures with C 10CS35

Dept of CSE,SJBIT 23

heoretically, one characteristic of a queue is that it does not have a specific capacity. Regardlessof how many elements are already contained, a new element can always be added. It can also beempty, at which point removing an element will be impossible until a new element has been

added again.Fixed length arrays are limited in capacity, but it is not true that items need to be copied towardsthe head of the queue. The simple trick of turning the array into a closed circle and letting thehead and tail drift around endlessly in that circle makes it unnecessary to ever move items storedin the array. If n is the size of the array, then computing indices modulo n will turn the array intoa circle. This is still the conceptually simplest way to construct a queue in a high level language,but it does admittedly slow things down a little, because the array indices must be compared tozero and the array size, which is comparable to the time taken to check whether an array index isout of bounds, which some languages do, but this will certainly be the method of choice for aquick and dirty implementation, or for any high level language that does not have pointer syntax.The array size must be declared ahead of time, but some implementations simply double thedeclared array size when overflow occurs. Most modern languages with objects or pointers canimplement or come with libraries for dynamic lists. Such data structures may have not specifiedfixed capacity limit besides memory constraints. Queue overflow results from trying to add anelement onto a full queue and queue underflow happens when trying to remove an element froman empty queue.A bounded queue is a queue limited to a fixed number of items.There are several efficient implementations of FIFO queues. An efficient implementation is onethat can perform the operations—enqueuing and dequeuing—in O(1) time.Linked listA doubly linked list has O(1) insertion and deletion at both ends, so is a natural choice forqueues.A regular singly linked list only has efficient insertion and deletion at one end. However, a smallmodification—keeping a pointer to the last node in addition to the first one—will enable it toimplement an efficient queue.A deque implemented using a modified dynamic array

5. Explain implenetation of circular queueus.(10m)(De-jan11)

Data Structures with C 10CS35

Dept of CSE,SJBIT 24

circular queue c program implementation. Queue is a data structure which uses FIFO (First infirst out) principle. Queue can be implemented as simple queue, dequeue and circular queue.Circular queue c is also implemented as same as simple queue, the main difference is that incircular queue last element will again points to first element as shown in figure. You can also seeprograms for implementing queue, stack and other data structure program.

circular queue c program implementation

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

struct Node

{

int Data;

struct Node* next;

}*rear, *front;

void delQueue()

{

struct Node *temp, *var=rear;

if(var==rear)

{

rear = rear->next;

free(var);

}

Data Structures with C 10CS35

Dept of CSE,SJBIT 25

else

printf("\nQueue Empty");

}

void push(int value)

{

struct Node *temp;

temp=(struct Node *)malloc(sizeof(struct Node));

temp->Data=value;

if (front == NULL)

{

front=temp;

front->next=NULL;

rear=front;

}

else

{

front->next=temp;

front=temp;

front->next=rear;

}

}

void display()

{

struct Node *var=rear;

if(var!=NULL)

{

Data Structures with C 10CS35

Dept of CSE,SJBIT 26

printf("\nElements are as: ");

while(var!=front)

{

printf("\t%d",var->Data);

var=var->next;

}

if(var==front)

{

printf("\t%d",var->Data);

}

printf("\n");

}

else

printf("\nQueue is Empty");

}

int main(int argc, char *argv[])

{

int i=0;

front=NULL;

printf(" \n1. Push to Queue");

printf(" \n2. Pop from Queue");

printf(" \n3. Display Data of Queue");

printf(" \n4. Exit\n");

while(1)

{

printf(" \nChoose Option: ");

Data Structures with C 10CS35

Dept of CSE,SJBIT 27

scanf("%d",&i);

switch(i)

{

case 1:

{

int value;

printf("\nEnter a valueber to push into Queue: ");

scanf("%d",&value);

push(value);

display();

break;

}

case 2:

{

delQueue();

display();

break;

}

case 3:

{

display();

break;

}

case 4:

{

exit(0);

Data Structures with C 10CS35

Dept of CSE,SJBIT 28

}

default:

{

printf("\nwrong choice for operation");

}

}

}

}

Data Structures with C 10CS35

Dept of CSE,SJBIT 29

UNIT 4LINKED LISTS

1. List out any two applications of linked list and any two advantages of doubly linkedlist over singly linked list.(10m)(June / July10)(Dec 2011)A linked list would be a reasonably good choice for implementing any of the following:1. Applications that have an MRU list (a linked list of file names)2. The cache in your browser that allows you to hit the BACK button (a linked list of URLs)3. Undo functionality in Photoshop or Word (a linked list of state)4. A stack, hash table, and binary tree can be implemented using a doubly linked list.5. A great way to represent a deck of cards in a game.Advantages:

1. We can traverse in both directions i.e. from starting to end and as well as from end to starting.2. It is easy to reverse the linked list.3. If we are at a node, then we can go to any node. But in linear linked list, it is not possible toreach the previous node.

Disadvantages:

1. It requires more space per space per node because one extra field is required for pointer toprevious node.2. Insertion and deletion take more time than linear linked list because more pointer operationsare required than linear linked list.

2. Write a C program to simulate an ordinary queue using a singly linked list.(10m)(June / July10), (Dec-Jan 2011), (Dec-Jan 2010)#include<stdio.h>#include<conio.h>#include<stdlib.h>struct Node{

int Data;struct Node* next;

}*rear, *front;

void delQueue(){

struct Node *temp, *var=rear;if(var==rear){

rear = rear->next;free(var);

}

Data Structures with C 10CS35

Dept of CSE,SJBIT 30

elseprintf("\nQueue Empty");

}

void push(int value){

struct Node *temp;temp=(struct Node *)malloc(sizeof(struct Node));temp->Data=value;if (front == NULL){

front=temp;front->next=NULL;rear=front;

}else{

front->next=temp;front=temp;front->next=NULL;

}}

void display(){

struct Node *var=rear;if(var!=NULL){

printf("\nElements are as: ");while(var!=NULL){

printf("\t%d",var->Data);var=var->next;

}printf("\n");}elseprintf("\nQueue is Empty");

}

int main(){

int i=0;front=NULL;printf(" \n1. Push to Queue");printf(" \n2. Pop from Queue");printf(" \n3. Display Data of Queue");printf(" \n4. Exit\n");

Data Structures with C 10CS35

Dept of CSE,SJBIT 31

while(1){

printf(" \nChoose Option: ");scanf("%d",&i);switch(i){

case 1:{

int value;printf("\nEnter a valueber to push into Queue: ");scanf("%d",&value);push(value);display();break;

}case 2:{

delQueue();display();break;

}case 3:{

display();break;

}case 4:{

exit(0);}default:{

printf("\nwrong choice for operation");}

}}

}

3. Give an algorithm to insert a node at a specified position for a given singlylinked list. ( 10m)(June / July11)//create new node

node *newNode = (node*)malloc(sizeof(node));

if(newNode == NULL){fprintf(stderr, "Unable to allocate memory for new node\n");exit(-1);

}

Data Structures with C 10CS35

Dept of CSE,SJBIT 32

newNode->value = val;

//check for first insertionif(head->next == NULL){

head->next = newNode;printf("added at beginning\n");

}

else{

//else loop through the list and find the last//node, insert next to itnode *current = head;while(current->next != NULL){

if(current->next == NULL){

current->next = newNode;printf("added later\n");

}current = current->next;

}}return 0;

}4. Write a C program to create a linked list and interchange the elements to the list atposition m and n and display contents of the list before and after interchanging theelements. (10m)(Dec-Jan 2010 )#include<stdio.h>#include<conio.h>struct list{int data;struct list *link;}*start=NULL;void creat(int);void swap();void disp();void main(){int ch,i,n,m;clrscr();do{printf(“\n1.create”);

Data Structures with C 10CS35

Dept of CSE,SJBIT 33

printf(“\n2.display”);printf(“\n3.Swap”);printf(“\n4.exit”);printf(“\nenter ur choice”);scanf(“%d”,&ch);switch(ch){case 1:printf(“\nHow many nodes”);scanf(“%d”,&n);for(i=0;i<n;i++){printf(“\nEnter the data”);scanf(“%d”,&m);creat(m);}break;case 2:disp();break;case 4:exit(0);case 3:swap();break;}}while(ch!=4);getch();}void creat(int m){struct list *tmp,*q;tmp=(struct list *)malloc(sizeof(struct list));tmp->data=m;tmp->link=NULL;if(start==NULL)start=tmp;else{q=start;while(q->link!=NULL)

Data Structures with C 10CS35

Dept of CSE,SJBIT 34

{q=q->link;}q->link=tmp;}}void disp(){struct list *q;if(start==NULL){printf(“list is empty”);}else{q=start;while(q!=NULL){printf(“%d->”,q->data);q=q->link;}}}void swap(){int m,n,i,tmp;struct list *q,*ptr,*ptr1;printf(“\nEnter the mth and nth position”);scanf(“%d%d”,&m,&n);for(i=1,ptr=start;i<m && ptr!=NULL;ptr=ptr->link,i++);for(i=1,ptr1=start;i<n && ptr1!=NULL;ptr1=ptr1->link,i++);if(ptr!=NULL && ptr1!=NULL){tmp=ptr->data;ptr->data=ptr1->data;ptr1->data=tmp;}else{printf(“\nPosition Not Found”);}

Data Structures with C 10CS35

Dept of CSE,SJBIT 35

5. Briefly explain the structures of different types of linked lists. Write a cfunction to count number of elements present in a singly linked list.(10m)(Jun-jul 11)Singly linked listSingly linked lists contain nodes which have a data field as well as a next field, which points to

the next node in the linked list.

A singly linked list whose nodes contain two fields: an integer value and a link to the next nodeDoubly linked listMain article: Doubly linked listIn a doubly linked list, each node contains, besides the next-node link, a second link fieldpointing to the previous node in the sequence. The two links may be calledforward(s)

and backwards, or next and prev(ious).

A doubly linked list whose nodes contain three fields: an integer value, the link forward to thenext node, and the link backward to the previous nodeA technique known as XOR-linking allows a doubly linked list to be implemented using a singlelink field in each node. However, this technique requires the ability to do bit operations onaddresses, and therefore may not be available in some high-level languages.Multiply linked listIn a multiply linked list, each node contains two or more link fields, each field being used toconnect the same set of data records in a different order (e.g., by name, by department, by date ofbirth, etc.). While doubly linked lists can be seen as special cases of multiply linked list, the factthat the two orders are opposite to each other leads tosimpler and more efficient algorithms, sothey are usually treated as a separate case.Circular listIn the last node of a list, the link field often contains a null reference, a special value used toindicate the lack of further nodes. A less common convention is to make it point to the first nodeof the list; in that case the list is said to be circular or circularly linked; otherwise it is said tobe open or linear.

A circular linked list

In the case of a circular doubly linked list, the only change that occurs is that the end, or "tail", ofthe said list is linked back to the front, or "head", of the list and vice versa.

Data Structures with C 10CS35

Dept of CSE,SJBIT 36

6. Write a c program to perform the following operations on doubly linked list : i)insert a node ii) delete a node. (Dec-Jan 2012)

#include"stdio.h"#include"alloc.h"struct node{

struct node *prev;int data;struct node *next;

};struct node *start;void insertbeg(void) // insert element at the beginning of DLL{

int a;struct node *nn;nn=(struct node *)malloc(sizeof(struct node));printf("enter data:");scanf("%d",&nn->data);a=nn->data;if(start==NULL) //If Linked list is empty{

nn->prev=nn->next=NULL;start=nn;

}else{

nn->next=start;nn->prev=NULL;start->prev=nn;start=nn;

}printf("%d succ. inserted\n",a);return;

}void insertend(void) // insert element at the End of DLL{

int b;struct node *nn,*lp;nn=(struct node *)malloc(sizeof(struct node));printf("enter data:");scanf("%d",&nn->data);

Data Structures with C 10CS35

Dept of CSE,SJBIT 37

b=nn->data;if(start==NULL){

nn->prev=nn->next=NULL;start=nn;

}else{

lp=start;while(lp->next!=NULL){

lp=lp->next;}nn->prev=lp;lp->next=nn;nn->next=NULL;

}printf("%d succ. inserted\n",b);return;

}void insertmid(void) // insert element before the given element of DLL{

struct node *nn,*temp,*ptemp;int x,c;if(start==NULL){

printf("dll is empty\n"); return;}printf("enter data before which new node is to be insreted\n");scanf("%d",&x);if(x==start->data){

insertbeg();return;

}ptemp=start;temp=start->next;while(temp!=NULL&&temp->data!=x){

ptemp=temp;temp=temp->next;

}if(temp==NULL)

Data Structures with C 10CS35

Dept of CSE,SJBIT 38

{printf("%d data does not exist\n",x);

}else{

nn=(struct node *)malloc(sizeof(struct node));printf("enter data");scanf("%d",&nn->data);c=nn->data;nn->prev=ptemp;nn->next=temp;ptemp->next=nn;temp->prev=nn;printf("%d succ. inserted\n",c);

}return;

}void deletion(void){

struct node *pt,*t,*nt;int x;if(start==NULL){

printf("dll is empty\n");return;

}printf("enter data to be deleted");scanf("%d",&x);if(x==start->data){

t=start;start=start->next;free(t);printf("%d is succ. deleted\n",x);if(start!=NULL){

start->prev=NULL;}return;

}pt=start;t=start->next;

Data Structures with C 10CS35

Dept of CSE,SJBIT 39

while(t!=NULL&&t->data!=x){

pt=t;t=t->next;

}if(t==NULL){

printf("%d does not exist\n",x);return;}else{

pt->next=t->next;if(t->next!=NULL){

nt=t->next;nt->prev=pt;

}free(t);

}printf("%d is succ. deleted\n",x);return;

}void display(void){

struct node *temp;if(start==NULL){

printf("dll is empty\n");return;

}printf("displaying in forword order\n");temp=start;while(temp!=NULL){

printf("%d\n",temp->data);temp=temp->next;

}return;

}void main(){

int c,a; start=NULL;

Data Structures with C 10CS35

Dept of CSE,SJBIT 40

do{

printf("1:insert\n2:delete\n3:display\n4:exit\nenter choice:");scanf("%d",&c);switch(c){

case 1:printf("1:insertbeg\n2:insert end\n3:insert mid\nenter choice:");scanf("%d",&a);switch(a){

case 1:insertbeg();break;case 2:insertend();break;case 3:insertmid();break;

}break;case 2:deletion();break;

case 3:display();break;case 4:printf("program ends\n");break;default:printf("wrong choice\n");break;

}}while(c!=4) ;

}7. Write short note on circular lists.(Dec-Jan 2012)

A circular linked list is a linked list in which the head element's previous pointer points to the tailelement and the tail element's next pointer points to the head element. In the special case of acircular list with only one element, the element's previous and next pointers point to itself, and itis both the head and tail of the list.

Programming a circular list presents some challenges, but the code is actually simpler and moreconcise than for a conventional linked list, because the lack of NULL pointers means that wenever need to check for them.

Defining the list and the nodes

Data Structures with C 10CS35

Dept of CSE,SJBIT 41

The list definition is the same as for a linked list except that, because the head and tail can easilybe defined in terms of each other, we only need to keep track of one of them. It is a matter oftaste which one we keep track of, and I have chosen the head.

struct MBcircularlist {

MBcnode * head;

unsigned int count;

};

typedef struct MBcircularlist MBcircularlist;

A circular list node is identical to a linked list node, with previous and next pointers and a voidpointer for the data.

struct MBcnode {

struct MBcnode * next;

struct MBcnode * previous;

void * data;

};

typedef struct MBcnode MBcnode;

When we create the nodes however, we will initialise the previous and next nodes to point to thenode itself rather than NULL. This will mean that we won't need to set them when we are addingthe first node to a list, just as initialising them to NULL did in the linked list.

Adding nodes

Adding nodes to a circular list is greatly simplified by our being able to rely on every nodehaving non-NULL previous and next pointers. This allows us to implement the four fundamentaladding operations - adding at the head, adding at the tail, adding before an element and addingafter an element - using one function and calling it with different nodes. I have used theMBcircularlist_insert_before() function for all of these operations.

Data Structures with C 10CS35

Dept of CSE,SJBIT 42

void MBcircularlist_insert_before(MBcircularlist * list, MBcnode * node, void * data)

{

MBcnode * newnode = MBcnode_create(data);

if (newnode) {

if (list->count > 0) {

newnode->next = node;

newnode->previous = node->previous;

newnode->previous->next = newnode;

node->previous = newnode;

}

else {

/* Adding the first element */

list->head = newnode;

}

list->count++;

}

}

In the case of adding at the head, we need to move the head pointer back one place so that thenew node becomes the head rather than the tail.

Iterating through a list

In a conventional linked list, you iterate by starting at the head and following the next pointersuntil you reach a NULL pointer. A while loop is ideal for this purpose. In the circular list,however, there is no NULL pointer to mark the end, so we need to follow the next pointers until

Data Structures with C 10CS35

Dept of CSE,SJBIT 43

we reach the pointer we started with. We can't use a while loop for this because its terminationcondition would already be true when it started. Instead we use a do loop, which tests itstermination condition at the bottom.

void MBcircularlist_for_each(const MBcircularlist * list, MBforfn forfn)

{

MBcnode * node = list->head;

if (node != NULL) {

do {

forfn(node->data);

node = node->next;

} while (node != list->head);

}

}

Removing nodes

As with adding nodes, the process of removing nodes is simplified by there being no NULLpointers, and we can implement all of the fundamental removal operations using one function.

void * MBcircularlist_remove_node(MBcircularlist * list, MBcnode * node)

{

void * data = NULL;

if (list->count > 0) {

if (node != node->next) { /* Or, list->count > 1 */

node->next->previous = node->previous;

node->previous->next = node->next;

Data Structures with C 10CS35

Dept of CSE,SJBIT 44

if (node == list->head)

list->head = list->head->next;

}

else {

/* Removing the last element */

list->head = NULL;

}

data = node->data;

MBcnode_delete(node);

list->count--;

}

return data;

}

Data Structures with C 10CS35

Dept of CSE,SJBIT 45

Unit 5TREES – 1

1. Define the following: (10m)( June / July10),(Dec-Jan 2010),(Jun-Jul 2011), (Dec-jan11)i) Binary treeBinary tree is a tree data structure in which each node has at most two child nodes, usuallydistinguished as "left" and "right". Nodes with children are parent nodes, and child nodes maycontain references to their parents. Outside the tree, there is often a reference to the "root" node(the ancestor of all nodes), if it exists. Any node in the data structure can be reached by startingat root node and repeatedly following references to either the left or right child. A tree whichdoes not have any node other than root node is called a null tree. In a binary tree, a degree ofevery node is maximum two. A tree with n nodes has exactly n−1 branches or degree.

ii) Complete binary tree

A complete binary tree is a binary tree in which every level, except possibly the last, iscompletely filled, and all nodes are as far left as possible.[3] A tree is called an almost completebinary tree or nearly complete binary tree if the exception holds, i.e. the last level is notcompletely filled. This type of tree is used as a specialized data structure called a heap.iii) Almost complete binary treeAn almost complete binary tree is a tree in which each nodethat has a right child also has a leftchild. Having a left child does not require a node to have a right child. Stated alternately, analmost complete binary tree is a tree where for a right child, there is always a left child, but for aleft child there may not be a right child.The number of nodes in a binary tree can be found usingthis formula: n = 2^h Where n is the amount of nodes in the tree, and h is the height of the tree.iv) Binary search treeBinary search tree (BST), sometimes also called an ordered or sorted binary tree, is a node-basedbinary tree data structure which has the following properties:[1]The left subtree of a node contains only nodes with keys less than the node's key.The right subtree of a node contains only nodes with keys greater than the node's key.The left and right subtree must each also be a binary search tree.There must be no duplicate nodes.v) Depth of a tree

Data Structures with C 10CS35

Dept of CSE,SJBIT 46

The number of elements in a complete, balanced, binary tree is N = 2D - 1, where D is the depth.

Simply solve for D...

N = 2D - 1

N + 1 = 2D

log2 (N + 1) = D

2. Given the following graph, write the inorder, preorder and postorder traversals.(10m)( June / July10) (Dec-jan11)

Pre-order traversal sequence: F, B, A, D, C, E, G, I, H (root, left, right)In-order traversal sequence: A, B, C, D, E, F, G, H, I (left, root, right)Post-order traversal sequence: A, C, E, D, B, H, I, G, F (left, right, root)

3. In brief describe any 4 applications of trees. (5m)(June / July11)

Applications of binary trees

Binary Search Tree - Used in many search applications where data is constantlyentering/leaving, such as the map and set objects in many languages' libraries. Binary Space Partition - Used in almost every 3D video game to determine what objectsneed to be rendered. Binary Tries - Used in almost every high-bandwidth router for storing router-tables. Hash Trees - used in p2p programs and specialized image-signatures in which a hashneeds to be verified, but the whole file is not available. Heaps - Used in implementing efficient priority-queues, which in turn are used forscheduling processes in many operating systems, Quality-of-Service in routers, and A* (path-finding algorithm used in AI applications, including robotics and video games). Also used inheap-sort. Huffman Coding Tree (Chip Uni) - used in compression algorithms, such as those usedby the .jpeg and .mp3 file-formats. GGM Trees - Used in cryptographic applications to generate a tree of pseudo-randomnumbers. Syntax Tree - Constructed by compilers and (implicitly) calculators to parse expressions. Treap - Randomized data structure used in wireless networking and memory allocation.

Data Structures with C 10CS35

Dept of CSE,SJBIT 47

T-tree - Though most databases use some form of B-tree to store data on the drive,databases which keep all (most) their data in memory often use T-trees to do so.

4. Construct a binary tree for : ((6+(3-2)*5)^2+3) .(5m)(June / July11)

5. Construct a binary tree from the traversal order given below: (10m)(Dec-Jan11)(Dec-Jan12)PREORDER = A B D E F C G H L J K

INORDER = D B F E A G C L J H K

Data Structures with C 10CS35

Dept of CSE,SJBIT 48

6. What is threaded binary tree? Explain right in and left in threaded binary trees.(10m)(June / July08), (Dec-Jan 2010)

A threaded binary tree defined as follows:"A binary tree is threaded by making all right child pointers that would normally be null point tothe inorder successor of the node, and all left child pointers that would normally be null point tothe inorder predecessor of the node."[1]A threaded binary tree makes it possible to traverse the values in the binary tree via a lineartraversal that is more rapid than a recursive in-order traversal. It is also possible to discover theparent of a node from a threaded binary tree, without explicit use of parent pointers or a stack,albeit slowly. This can be useful where stack space is limited, or where a stack of parent pointersis unavailable (for finding the parent pointer via DFS).To see how this is possible, consider a node k that has a right child r. Then the left pointer of rmust be either a child or a thread back to k. In the case that r has a left child, that left child mustin turn have either a left child of its own or a thread back to k, and so on for all successive leftchildren. So by following the chain of left pointers from r, we will eventually find a thread

pointing back to k. The situation is symmetrically similar when q is the left child of p—we canfollow q's right children to a thread pointing ahead to p.

Data Structures with C 10CS35

Dept of CSE,SJBIT 49

Data Structures with C 10CS35

Dept of CSE,SJBIT 50

Unit 6TREES – 2, GRAPHS

1. Write c function for the following tree traversals: i)inorder ii)preorder iii)postorder(10m)(Jun-Jul-2010)(dec 2011).

Traversing a tree involves iterating (looping) over all nodes in some manner. Because from agiven node there is more than one possible next node (it is not a linear data structure), then,assuming sequential computation (not parallel), some nodes must be deferred – stored in someway for later visiting. This is often done via a stack (LIFO) or queue (FIFO). As a tree is a self-referential (recursively defined) data structure, traversal can naturally be describedby recursion or, more subtly, corecursion, in which case the deferred nodes are stored implicitly– in the case of recursion, in the call stack.

The name given to a particular style of traversal comes from the order in which nodes are visited.Most simply, does one go down first (depth-first: first child, then grandchild before second child)or across first (breadth-first: first child, then second child before grandchildren)? Depth-firsttraversal is further classified by position of the root element with regard to the left and rightnodes. Imagine that the left and right nodes are constant in space, then the root node could beplaced to the left of the left node (pre-order), between the left and right node (in-order), or to theright of the right node (post-order). There is no equivalent variation in breadth-first traversal –given an ordering of children, "breadth-first" is unambiguous.

For the purpose of illustration, it is assumed that left nodes always have priority over right nodes.This ordering can be reversed as long as the same ordering is assumed for all traversal methods.

Depth-first traversal is easily implemented via a stack, including recursively (via the call stack),while breadth-first traversal is easily implemented via a queue, including corecursively.

Beyond these basic traversals, various more complex or hybrid schemes are possible, suchas depth-limited searches such as iterative deepening depth-first search.

Depth-first

There are three types of depth-first traversal: pre-order, in-order and post-order. For a binarytree, they are defined as operations recursively at each node, starting with the root node follows:

Pre-order:

1. Visit the root.2. Traverse the left subtree.3. Traverse the right subtree.

In-order (symmetric):

1. Traverse the left subtree.2. Visit the root.

Data Structures with C 10CS35

Dept of CSE,SJBIT 51

3. Traverse the right subtree.

Post-order:

1. Traverse the left subtree.2. Traverse the right subtree.3. Visit the root.

The trace of a traversal is called a sequentialization of the tree. No one sequentialisationaccording to pre-, in- or post-order describes the underlying tree uniquely. Either pre-order orpost-order paired with in-order is sufficient to describe the tree uniquely, while pre-order withpost-order leaves some ambiguity in the tree structure.[2]

Generic tree

To traverse any tree in depth-first order, perform the following operations recursively at eachnode:

1. Perform pre-order operation2. for i=1 to n-1 do

1. Visit child[i], if present

2. Perform in-order operation3. Visit child[n], if present4. Perform post-order operation

where n is the number of child nodes. Depending on the problem at hand, the pre-order, in-orderor post-order operations may be void, or you may only want to visit a specific child node, sothese operations are optional. Also, in practice more than one of pre-order, in-order and post-order operations may be required. For example, when inserting into a ternary tree, a pre-orderoperation is performed by comparing items. A post-order operation may be needed afterwards tore-balance the tree.

Breadth-first

Trees can also be traversed in level-order, where we visit every node on a level before going to alower level.

Uses

Pre-order traversal while duplicating nodes and values can make a complete duplicate of a binarytree. It can also be used to make a prefix expression (Polish notation) from expression trees:traverse the expression tree pre-orderly.

In-order traversal is very commonly used on binary search trees because it returns values fromthe underlying set in order, according to the comparator that set up the binary search tree (hencethe name).

Post-order traversal while deleting or freeing nodes and values can delete or free an entire binarytree. It can also generate a postfix representation of a binary tree.

Data Structures with C 10CS35

Dept of CSE,SJBIT 52

Example

Binary tree:

Depth-firstPre-order traversal sequence: F, B, A, D, C, E, G, I, H (root, left, right)

Data Structures with C 10CS35

Dept of CSE,SJBIT 53

In-order traversal sequence: A, B, C, D, E, F, G, H, I (left, root, right)

Post-order traversal sequence: A, C, E, D, B, H, I, G, F (left, right, root)

Breadth-first

Level-order traversal sequence: F, B, G, A, D, I, C, E, H

2. Explain the following with an example: i) forest ii) graph iii) winner tree(8m)(Jun-Jul10)A forest is a collection of one or more Windows 2000 Active Directory trees, organized as peersand connected by two-way, transitive trust relationships A single domain constitutes a tree of one

Data Structures with C 10CS35

Dept of CSE,SJBIT 54

domain, and a single tree constitutes a forest of one tree. Thus, a forest is synonymous withActive Directory — that is, the set of all directory partitions in a particular directory serviceinstance (which includes all domains and all configuration and schema information) makes up aforest.A graph data structure consists of a finite (and possibly mutable) set of ordered pairs, callededges or arcs, of certain entities called nodes or vertices. As in mathematics, an edge (x,y) is saidto point or go from x to y. The nodes may be part of the graph structure, or may be externalentities represented by integer indices or references.

A winner tree for n players is a complete binary tree with n external nodes and n-1 internal

nodes. Each internal node records the winner of the match. To determine the winner of a match,we assume that each player has a value In a min (max) winner tree, the player with the smaller(larger) value wins

3. Describe the binary search tree with an example. Write a iterative function to searchfor a key value in a binary search tree .(8m)(dec 2011)(Jun-Jul11)Binary search tree (BST), sometimes also called an ordered or sorted binary tree, is a node-basedbinary tree data structure which has the following properties: The left subtree of a node containsonly nodes with keys less than the node's key. The right subtree of a node contains only nodeswith keys greater than the node's key.

Data Structures with C 10CS35

Dept of CSE,SJBIT 55

The left and right subtree must each also be a binary search tree. There must be no duplicatenodes.Generally, the information represented by each node is a record rather than a single data element.However, for sequencing purposes, nodes are compared according to their keys rather than anypart of their associated records.The major advantage of binary search trees over other data structures is that the related sortingalgorithms and search algorithms such as in-order traversal can be very efficient.Binary search trees are a fundamental data structure used to construct more abstract datastructures such as sets, multisets, and associative arrays.Node* Search(int key, Node* node){

if ( node == NULL )return NULL;

else if ( node->Key() == key )return node;

else if ( key <= node->Key() )Search(key, node->Left());

else if ( key > node->Key() )Search(key, node->Right());

elsereturn NULL;

}

4. Explain representation of disjoint sets.(4m)( dec 2011 )(Jun-Jul10)In computing, a disjoint-set data structure is a data structure that keeps track of a set of elementspartitioned into a number of disjoint (nonoverlapping) subsets. A union-find algorithm is analgorithm that performs two useful operations on such a data structure:Find: Determine which subset a particular element is in. This can be used fordetermining if two elements are in the same subset.Union: Join two subsets into a single subset.Because it supports these two operations, a disjoint-set data structure is sometimes called aunion-find data structure or merge-find set. The otherimportant operation, MakeSet, whichmakes a set containing only a given element (a singleton), is generally trivial. With these three

operations, many practical partitioning problems can be solved (see the Applications section).In order to define these operations more precisely, some way of representing the sets is needed.One common approach is to select a fixed element of each set, called its representative, to

Data Structures with C 10CS35

Dept of CSE,SJBIT 56

represent the set as a whole. Then, Find(x) returns the representative of the set that x belongs to,and Union takes two set representatives as its arguments.

5. Explain heap and heap sort.(10m)(dec 2011)( dec 2012)Heapsort is a comparison-based sorting algorithm to create a sorted array (or list), and is part ofthe selection sort family. Although somewhat slower in practice on most machines than a well-implemented quicksort, it has the advantage of a more favorable worst-case O(n log n) runtime.Heapsort is an in-place algorithm, but it is not astable sortThe heapsort algorithm can be divided into two parts.In the first step, a heap is built out of the data.In the second step, a sorted array is created by repeatedly removing the largest element from theheap, and inserting it into the array. The heap is reconstructed after each removal. Once allobjects have been removed from the heap, we have a sorted array. The direction of the sortedelements can be varied by choosing a min-heap or max-heap in step one.Heapsort can be performed in place. The array can be split into two parts, the sorted array andthe heap. The storage of heaps as arrays is diagrammed here. The heap's invariant is preservedafter each extraction, so the only cost is that of extraction.The most important variation to the simple variant is an improvement by R. W. Floyd that, inpractice, gives about a 25% speed improvement by using only one comparison in each siftup run,which must be followed by a siftdown for the original child. Moreover, it is more elegant toformulate. Heapsort's natural way of indexing works on indices from 1 up to the number ofitems. Therefore the start address of the data should be shifted such that this logic can beimplemented avoiding unnecessary +/- 1 offsets in the coded algorithm. The worst-case numberof comparisons during the Floyd's heap-construction phase of Heapsort is known to be equal to2N − 2s2(N) − e2(N), where s2(N) is the sum of all digits of the binary representation of N ande2(N) is the exponent of 2 in the prime factorization of N.[2]Ternary heapsort[3] uses a ternary heap instead of a binary heap; that is, each element in the heaphas three children. It is more complicated to program, but does a constant number of times fewerswap and comparison operations. This is because each step in the shift operation of a ternaryheap requires three comparisons and one swap, whereas in a binary heap two comparisons andone swap are required. The ternary heap does two steps in less time than the binary heap requiresfor three steps, which multiplies the index by a factor of 9 instead of the factor 8 of three binarysteps. Ternary heapsort is about 12% faster than the simple variant of binary heapsort.[citationneeded]The smoothsort algorithm[4][5] is a variation of heapsort developed by Edsger Dijkstra in 1981.Like heapsort, smoothsort's upper bound is O(n log n). The advantage of smoothsort is that itcomes closer to O(n) time if the input is already sorted to some degree, whereas heapsortaverages O(n log n) regardless of the initial sorted state. Due to its complexity, smoothsort israrely used.Levcopoulos and Petersson[6] describe a variation of heapsort based on a Cartesian tree that doesnot add an element to the heap until smaller values on both sides of it have already been includedin the sorted output. As they show, this modification can allow the algorithm to sort morequickly than O(n log n) for inputs that are already nearly sorted.

6. WAP to implement min heap(8m)(dec 2011)(Jun-Jul11)

#include<stdio.h>#include<conio.h>

Data Structures with C 10CS35

Dept of CSE,SJBIT 57

int main(){

int TREE[10],N,i,j,K,p,c,temp;printf("\n\n Enter no of elements..");scanf("%d",&N);printf("\n\n Enter the nos..");for(i=1;i<=N;i++)scanf("%d",&TREE[i]);for(i=2;i<=N;i++){

K=i;do{

if(TREE[K]>TREE[K/2]) // Values are inserted in the heap{

temp=TREE[K];TREE[K]=TREE[K/2];TREE[K/2]=temp;

}p=K/2;K=p;

}while(K!=0);

}printf("\n\n\n On inserting values are arranged as \n");for(i=1;i<=N;i++) // Displaying values in heapprintf("%d\t",TREE[i]);for(j=N;j>0;j--){

temp=TREE[1];TREE[1]=TREE[j];TREE[j]=temp;p=0;do{ // Heap sorting is applied

c=2*p+2;if((TREE[c][/c]<TREE[c language="+1"][/c]) && c<j-1)c++;if(TREE[p]<TREE[c][/c] && c<j){

temp=TREE[p];TREE[p]=TREE[c][/c];TREE[c][/c]=temp;

}p=c;}while(c<(j+1));

}

Data Structures with C 10CS35

Dept of CSE,SJBIT 58

printf("\n\n\n The sorted nos are..");for(i=1;i<=N;i++) // printing the heap in sorted orderprintf("%d\t",TREE[i]);getch();

}

7. Explain min and max heap with example.(10m)(Dec 2012)

A data structure with the shape described above becomes useful if data within it is organised, sothat the key of every node is smaller or equal to the keys of its 2 (or sometimes one) children.For a child to have a key smaller than that of its parent would violate this condition. When a heapis organised like this, it can be useful as a priority queue, because the lowest key will always beat the top of the heap and most easy to remove. This is called a min heap. This ordering propertyis reversed (a max heap) if it is desired for the highest key should always to be removed first.When a heap is ordered in this manner, insertion and removal of keys will require movement ofnodes along a single path from the top to bottom. As the maximum lengths of insertion anddeletion bubbling paths is log2n for a heap containing n nodes, this value enables us to derive themaximum numbers of comparisons and moves.

UNIT 7PRIORITY QUEUES

1. What is binomial heap? Explain the steps involved in the deletion of minelement from a binomial heap. (10m)(Dec-Jan10)(jun-Jul11)(dec 2011)

In computer science, a binomial heap is a heap similar to a binary heap but also supports quickmerging of two heaps. This is achieved by using a special tree structure. It is important as animplementation of the mergeable heap abstract data type (also called meldable heap), which isa priority queue supporting merge operation.A binomial heap is implemented as a collection of binomial trees (compare with a binary heap,

Data Structures with C 10CS35

Dept of CSE,SJBIT 59

which has a shape of a single binary tree). A binomial tree is defined recursively:A binomial tree of order 0 is a single nodeA binomial tree of order k has a root node whose children are roots of binomial trees of ordersk−1, k−2, ..., 2, 1, 0 (in this order).A binomial tree of order k has 2k nodes, height k.Because of its unique structure, a binomial tree of order k can be constructed from two trees oforder k−1 trivially by attaching one of them as the leftmost child of root of the other one. Thisfeature is central to the merge operation of a binomial heap, which is its major advantage overother conventional heaps.The name comes from the shape: a binomial tree of order has nodes at depth .

A binomial heap is implemented as a set of binomial trees that satisfy the binomial heapproperties:

Each binomial tree in a heap obeys the minimum-heap property: the key of a node isgreater than or equal to the key of its parent.

There can only be either one or zero binomial trees for each order, including zero order.

The first property ensures that the root of each binomial tree contains the smallest key in the tree,which applies to the entire heap.

The second property implies that a binomial heap with n nodes consists of at most log n + 1binomial trees. In fact, the number and orders of these trees are uniquely determined by thenumber of nodes n: each binomial tree corresponds to one digit in the binary representation of

number n. For example number 13 is 1101 in binary, , and thus a binomial heapwith 13 nodes will consist of three binomial trees of orders 3, 2, and 0 (see figure below).

Data Structures with C 10CS35

Dept of CSE,SJBIT 60

2. Define Fibonacci heap. Briefly explain the different types.(10m)(dec2011)(Jun-Jul10)(Dec-Jan12)

Fibonacci heap is a heap data structure consisting of a collection of trees. It has abetter amortized running time than a binomial heap. Fibonacci heaps were developed by MichaelL. Fredman and Robert E. Tarjan in 1984 and first published in a scientific journal in 1987. Thename of Fibonacci heap comes from Fibonacci numbers which are used in the running timeanalysis.Find-minimum is O(1) amortized time.[1] Operations insert, decrease key, and merge (union)work in constant amortized time.[2] Operations delete and delete minimum work in O(log n)amortized time.[2] This means that starting from an empty data structure, any sequenceof a operations from the first group and b operations from the second group wouldtake 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 heapwhen b is asymptotically smaller than a.Using Fibonacci heaps for priority queues improves the asymptotic running time of importantalgorithms, such as Dijkstra's algorithm for computing the shortest pathbetween two nodes in agraph.

A Fibonacci heap is a collection of trees satisfying the minimum-heap property, that is, the keyof a child is always greater than or equal to the key of the parent. This implies that the minimumkey is always at the root of one of the trees. Compared with binomial heaps, the structure of aFibonacci heap is more flexible. The trees do not have a prescribed shape and in the extreme casethe heap can have every element in a separate tree. This flexibility allows some operations to beexecuted in a "lazy" manner, postponing the work for later operations. For example mergingheaps is done simply by concatenating the two lists of trees, and operation decreasekey sometimes cuts a node from its parent and forms a new tree.

However at some point some order needs to be introduced to the heap to achieve the desiredrunning time. In particular, degrees of nodes (here degree means the number of children) are kept

Data Structures with C 10CS35

Dept of CSE,SJBIT 61

quite low: every node has degree at most O(log n) and the size of a subtree rooted in a node ofdegree k is at least Fk + 2, where Fk is the kth Fibonacci number. This is achieved by the rule thatwe can cut at most one child of each non-root node. When a second child is cut, the node itselfneeds to be cut from its parent and becomes the root of a new tree (see Proof of degree bounds,below). The number of trees is decreased in the operation delete minimum, where trees are linkedtogether.

As a result of a relaxed structure, some operations can take a long time while others are donevery quickly. For theamortized running time analysis we use the potential method, in that wepretend that very fast operations take a little bit longer than they actually do. This additional timeis then later combined and subtracted from the actual running time of slow operations. Theamount of time saved for later use is measured at any given moment by a potential function. Thepotential of a Fibonacci heap is given by

Potential = t + 2m

where t is the number of trees in the Fibonacci heap, and m is the number of marked nodes. Anode is marked if at least one of its children was cut since this node was made a child of anothernode (all roots are unmarked).

Thus, the root of each tree in a heap has one unit of time stored. This unit of time can be usedlater to link this tree with another tree at amortized time 0. Also, each marked node has two unitsof time stored. One can be used to cut the node from its parent. If this happens, the node becomesa root and the second unit of time will remain stored in it as in any other root.

3. Explain priority queue?(10m)(dec09/jan10)(jun-Jul11)(Dec-Jan12)

A priority queue is an abstract data type which is like a regular queue or stack data structure,but where additionally each element has a "priority" associated with it. In a priority queue, anelement with high priority is served before an element with low priority. If two elements havethe same priority, they are served according to their order in the queue.

stack — elements are pulled in last-in first-out-order (e.g. a stack of papers) queue — elements are pulled in first-in first-out-order (e.g. a line in a cafeteria)

Data Structures with C 10CS35

Dept of CSE,SJBIT 62

It is a common misconception that a priority queue is a heap. A priority queue is an abstractconcept like "a list" or "a map"; just as a list can be implemented with alinked list or an array, apriority queue can be implemented with a heap or a variety of other methods.

A priority queue must at least support the following operations:

insert_with_priority: add an element to the queue with an associated priority

pull_highest_priority_element: remove the element from the queue that has the highestpriority, and return it

This is also known as "pop_element(Off)", "get_maximum_element", or

"get_front(most)_element".

Some conventions reverse the order of priorities, considering lower values to be higher priority,

so this may also be known as "get_minimum_element", and is often referred to as "get-min" in

the literature.

This may instead be specified as separate "peek_at_highest_priority_element" and

"delete_element" functions, which can be combined to produce "pull_highest_priority_element".

In addition, peek (in this context often called find-max or find-min), which returns the highestpriority element but does not modify the queue, is very frequently implemented, and nearlyalways executes in O(1) time. This operation and its O(1) performance is crucial to manyapplications of priority queues.

More advanced implementations may support more complicated operations, suchas pull_lowest_priority_element, inspecting the first few highest- or lowest-priority elements,clearing the queue, clearing subsets of the queue, performing a batch insert, merging two or morequeues into one, incrementing priority of any element

4. Explain pairing heaps.(10m)(Dec-Jan11)(Jun-Jul10)

A pairing heap is a type of heap data structure with relatively simple implementation andexcellent practical amortized performance. However, it has proven very difficult to determine theprecise asymptotic running time of pairing heaps.Pairing heaps are heap ordered multiway trees. Describing the various heap operations isrelatively simple (in the following we assume a min-heap):find-min: simply return the top element of the heap.merge: compare the two root elements, the smaller remains the root of the result, the largerelement and its subtree is appended as a child of this root.insert: create a new heap for the inserted element and merge into the original heap.decrease-key (optional): remove the subtree rooted at the key to be decreased then merge it withthe heap.delete-min: remove the root and merge its subtrees. Various strategies are employed.The amortized time per delete-min is .[1] The operations find-min, merge, and insert are [2] anddecrease-key takes amortized time.[3] Fredman proved that the amortized time per decrease-keyis at least .[4]Although this is worse than other priority queue algorithms such as Fibonacci heaps, which

Data Structures with C 10CS35

Dept of CSE,SJBIT 63

perform decrease-key in amortized time, the performance in practice is excellent. Stasko andVitter[5] and Moret and Shapiro[6] conducted experiments on pairing heaps and other heap datastructures. They concluded that the pairing heap is as fast as, and often faster than, other efficientdata structures like the binary heaps.

find-min[edit]The function find-min simply returns the root element of the heap:function find-min(heap)

if heap == Emptyerror

elsereturn heap.elem

merge[edit]Merging with an empty heap returns the other heap, otherwise a new heap is returned that has theminimum of the two root elements as its root element and just adds the heap with the larger rootto the list of subheaps:function merge(heap1, heap2)

if heap1 == Emptyreturn heap2

elsif heap2 == Emptyreturn heap1

elsif heap1.elem < heap2.elemreturn Heap(heap1.elem, heap2 :: heap1.subheaps)

elsereturn Heap(heap2.elem, heap1 :: heap2.subheaps)

insert[edit]The easiest way to insert an element into a heap is to merge the heap with a new heap containingjust this element and an empty list of subheaps:function insert(elem, heap)

return merge(Heap(elem, []), heap)

delete-min[edit]The only non-trivial fundamental operation is the deletion of the minimum element from the heap.The standard strategy first merges the subheaps in pairs (this is the step that gave thisdatastructure its name) from left to right and then merges the resulting list of heaps from right toleft:function delete-min(heap)

if heap == Emptyerror

elsereturn merge-pairs(heap.subheaps)

5. Note on (Repeated) (10m) ( Jun-Jul10)(Dec-Jan12)Fibbonacci heap.pairning heap

Data Structures with C 10CS35

Dept of CSE,SJBIT 64

UNIT-8

EFFICIENT BINARY SEARCH TREES

1. Describe the following with an eg: i) height balanced trees ii) optimal bst.(10m)(Jun-Jul10) )(Dec-Jan12)In order to prevent a tree unbalance, with height-balanced trees we associate a balance indicator

with each node in the tree. This indicator will contain one of the three values which we denoteas left(L), right(R), or balance(B), according to the following defenitions.Left: A node will be called left heavy if the longest path in its left subtree is one longer than thelongest path of its right subtree.Balance: A node will be called balanced if the longest paths in both of its subtrees are equal.Right: A node will be called right heavy if the longest path in its right subtree is one longer thanthe longest path of its left subtree.

In a balanced tree each node must be in one of these three states. If there exists a nodein a tree where this is not true, then such a tree is said to be unbalanced.

6 5/ \ \

5 9 6/ / \ \

4 8 11 7

Balanced tree Unbalanced tree

A new node is inserted at the leaf or terminal node level. The only nodes which canhave their balance indicator changed by such an insertion are those which lie on a path betweenthe root of the tree and the newly inserted leaf. The possible changes which can occur to a nodeon this path are as follows:

1. The node was either left or right heavy and has now become balanced.2. The node was balanced and has now become left or right heavy.3. The node was heavy and the new node has been inserted in the heavy subtree, thus

creating an unbalanced subtree. Such a node is said to be a critical node.

2. Explain the Red-black tree. State its properties.? (10m)(dec09/jan10)(jun-Jul11)(Dec-Jan12)A red–black tree is a type of self-balancing binary search tree, a data structure used in computerscience.The self-balancing is provided by painting each node with one of two colors (these are typicallycalled 'red' and 'black', hence the name of the trees) in such a way that the resulting painted treesatisfies certain properties that don't allow it to become significantly unbalanced. When the treeis modified, the new tree is subsequently rearranged and repainted to restore the coloringproperties. The properties are designed in such a way that this rearranging and recoloring can beperformed efficiently.The balancing of the tree is not perfect but it is good enough to allow it to guarantee searching inO(log n) time, where n is the total number of elements in the tree. The insertion, and deletionoperations, along with the tree rearrangement and recoloring are also performed in O(log n)time.[1]

Data Structures with C 10CS35

Dept of CSE,SJBIT 65

Tracking the color of each node requires only 1 bit of information per node because there are

only two colors. The tree does not contain any other data specific to its being a red–black tree soits memory footprint is almost identical to classic (uncolored) binary search tree. In many casesthe additional bit of information can be stored at no additional memory cost.

3. Explain AVL tree.(10m)(Jun-Jul10)AVL tree (Adelson-Velskii and Landis' tree, named after the inventors) is a self-balancing binarysearch tree, and it was the first such data structure to be invented.[1] In an AVL tree, the heightsof the two child subtrees of any node differ by at most one; if at any time they differ by morethan one, rebalancing is done to restore this property. Lookup, insertion, and deletion all takeO(log n) time in both the average and worst cases, where n is the number of nodes in the treeprior to the operation. Insertions and deletions may require the tree to be rebalanced by one ormore tree rotations.The AVL tree is named after its two Soviet inventors, G. M. Adelson-Velskii and E. M. Landis,who published it in their 1962 paper "An algorithm for the organization of information".[2]AVL trees are often compared with red-black trees because they both support the same set ofoperations and take O(log n) time for the basic operations. For lookup-intensive applications,they are faster than red-black trees because they are more rigidly balanced.[3] Similar to red-black trees, AVL trees are height-balanced, but in general not weight-balanced nor μ-balancedfor any ;[4] that is, sibling nodes can have hugely differing numbers of descendants.

Data Structures with C 10CS35

Dept of CSE,SJBIT 66

4. Write a note on: pointers, heap, and algorithm to evaluate postfix expression.(20m)(Dec-Jan12)(repeated)5. Write a note on binomial heap, stack, and queue. (20m)(Dec-Jan11)(repeated)6. Write a note on circular queues.(10m)(Jun-Jul11)(repeated)