section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and...

125
Table of Contents S.No Name of the Project Page No. 1 Develop a project to find the solution for the maximum subsequence sum problem with different time complexity solutions. 2 Develop a project to test Linear and Binary searching techniques 3 Develop a project to test Insertion and shell sorting techniques 4 Develop a project to test Merge and Quick sorting techniques(Devide and conquer method) 5. Develop a project to test operations in array implementation of stacks and queues. 6. Develop a project to convert an infix to postfix Expression and evaluate a postfix expression. 7 Develop a project to implement all operations on Single Linked List. 8 Develop a project to implement all operations on Double Linked List. 9 Develop a project to implement polynomial Operations. 10 Develop a project to create a binary search tree and perform insertion, deletion and traversal operation on it. 1

Transcript of section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and...

Page 1: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

Table of Contents

S.No Name of the Project Page No.

1 Develop a project to find the solution for the maximum subsequence sum problem with different time complexity solutions.

2 Develop a project to test Linear and Binary searching techniques

3 Develop a project to test Insertion and shell sorting techniques

4 Develop a project to test Merge and Quick sorting techniques(Devide and conquer method)

5. Develop a project to test operations in array implementation of stacks and queues.

6. Develop a project to convert an infix to postfix Expression and evaluate a postfix expression.

7 Develop a project to implement all operations on Single Linked List.

8 Develop a project to implement all operations on Double Linked List.

9 Develop a project to implement polynomial Operations.

10 Develop a project to create a binary search tree and perform insertion, deletion and traversal operation on it.

11 Develop a project to resolve collision resolving problem in hash table with separate chaining hashing technique.

12 Develop a project to test operations in Linked list implementation stacks and queues.

13. Develop a project to test AVL tree operations.

14. Develop a project to test all operations on circular linked list.

1

Page 2: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

15. Develop a project to test Heap sort.

16. Develop a project for Airport simulation

(Applying Queue)

17. Develop a project for Car GarageSimulation (Applying De-queue and stack )

18. Develop a Project for Simulate a Dictionary (applying Linear Search)

19. Develop a project for finding Duplicate files in a system by Applying Binary search technique.

20. Develop a project for Sorting the records using Sorting techniques.

2

Page 3: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

PROJECT NO : 1

MAXIMUM SUBSEQUENCE SUM

Learning Objectives:

To learn about:

How to solve a problem with different complexities.

To understand time complexity.

How to select best algorithm based on their time complexity.

Problem Description:

A Program to solve maximum subsequence sum problem with Linear time complexity.

(The Maximum Contiguous Subsequence Sum (MCSS) Problem). Given a sequenceof numbers s = hs1, . . . , sni, the maximum contiguous subsequence sum problem is to find

. (i.e., the sum of the contiguous subsequence of s that has the largest value).Let’s look at an example. For s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such subsequences, we’re interested in finding one that maximizies the sum. In this particular example, we can check that mcss(s) = 4, achieved by taking the subsequence {2,-1, 3}.

Input: A sequence {x1, x2,…. Xn} of integers. (Some of the integers may be negative.)

Output: The maximum sum over all subsequences.

H/W & S/W Specifications:Pentium –IV

Putty software

Linux Server with c compiler

Source Code:

#include<stdio.h>

#include<conio.h>

int max3(int x, int y, int z)

{

if(x>y)

{

if(x>z)

return(x);

3

Page 4: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

else return z;

}

else if(y>z) return y;

else return z;

}

int alg3( int a[], unsigned int n )

{

int this_sum, max_sum, best_i, best_j, i, j, k;

/*1*/ max_sum = 0; best_i = best_j = -1;

/*2*/ for( i=0; i<n; i++ )

/*3*/ for( j=i; j<n; j++ )

{

/*4*/ this_sum=0;

/*5*/ for( k = i; k<=j; k++ )

/*6*/ this_sum += a[k];

/*7*/ if( this_sum > max_sum )

{ /* update max_sum, best_i, best_j */

/*8*/ max_sum = this_sum;

/*9*/ best_i = i;

/*10*/ best_j = j;

}

}

/*11*/ return( max_sum );

}

int alg2( int a[], unsigned int n )

{

int this_sum, max_sum, /*best_i, best_j,*/ i, j, k;

/*1*/ max_sum = 0; /*best_i = best_j = -1;*/

/*2*/ for( i=0; i<n; i++ )

{

/*3*/ this_sum = 0;

/*4*/ for( j=i; j<n; j++ )

{

4

Page 5: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

/*5*/ this_sum += a[j];

/*6*/ if( this_sum > max_sum )

/* update max_sum, best_i, best_j */

max_sum = this_sum;

}

}

/*7*/ return( max_sum );

}

int nlgn( int a[], unsigned int n )

{

return max_sub_sum( a, 0, n-1 );

}

int max_sub_sum( int a[], int left, int right )

{

int max_left_sum, max_right_sum;

int max_left_border_sum, max_right_border_sum;

int left_border_sum, right_border_sum;

int center, i;

/*1*/ if ( left == right ) /* Base Case */

/*2*/ if( a[left] > 0 )

/*3*/ return a[left];

else

/*4*/ return 0;

/*5*/ center = (left + right )/2;

/*6*/ max_left_sum = max_sub_sum( a, left, center );

/*7*/ max_right_sum = max_sub_sum( a, center+1, right );

/*8*/ max_left_border_sum = 0; left_border_sum = 0;

/*9*/ for( i=center; i>=left; i-- )

{

/*10*/ left_border_sum += a[i];

/*11*/ if( left_border_sum > max_left_border_sum )

/*12*/ max_left_border_sum = left_border_sum;

}

/*13*/ max_right_border_sum = 0; right_border_sum = 0;

/*14*/ for( i=center+1; i<=right; i++ )

{

5

Page 6: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

/*15*/ right_border_sum += a[i];

/*16*/ if( right_border_sum > max_right_border_sum )

/*17*/ max_right_border_sum = right_border_sum;

}

/*18*/ return max3( max_left_sum, max_right_sum,

max_left_border_sum + max_right_border_sum );

}

int lgn( int a[], unsigned int n )

{

int this_sum, max_sum, best_i, best_j, i, j;

/*1*/ i = this_sum = max_sum = 0; best_i = best_j = -1;

/*2*/ for( j=0; j<n; j++ )

{

/*3*/ this_sum += a[j];

/*4*/ if( this_sum > max_sum )

{ /* update max_sum, best_i, best_j */

/*5*/ max_sum = this_sum;

/*6*/ best_i = i;

/*7*/ best_j = j;

}

else

/*8*/ if( this_sum < 0 )

{

/*9*/ i = j + 1;

/*10*/ this_sum = 0;

}

}

/*11*/ return( max_sum );

}

void main()

{

int a[20],i,j,n,sum,ch;

int alg4(int[],int);

clrscr();

printf("Enter N value: ");

6

Page 7: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

scanf("%d",&n);

printf("\nEnter Array values: \n");

for(i=0;i<n;i++)

scanf("%d",&a[i]);

while(1)

{

printf("\nSelect one of the time complexity algorithm:\n");

printf("1. With cubic complexity\n");

printf("2. With Quadratic complexity\n");

printf("3. With nlogn Complexity\n");

printf("4. With Linear Complexity\n");

printf("5. Exit\n");

printf("Enter your choice :");

scanf("%d",&ch);

switch(ch)

{

case 1: sum=alg3(a,n); break;

case 2: sum=alg2(a,n); break;

case 3: sum=nlgn(a,n); break;

case 4: sum=lgn(a,n); break;

case 5: exit();

default: printf("Enter Propere choice\n"); break;

}

printf("\nsum of linear alg is: %d\n",sum);

}

}

Result:Enter n value 6Enter array values -2 11 -4 13 -5 -2 Sum of linear alg is : 20

Date: Signature of Instructor

7

Page 8: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

PROJECT NO : 2

SEARCHING

Learning Objectives:

To learn about:

Simple Searching Techniques

Linear Search

Binary Search

Problem Description:

Searching is the process of finding an element in the given list. Here we have two popular

methods to implement this concept.

In Linear searching Searching will be done in linear passion Starting from the first element.

In a Binary search or half-interval search algorithm finds the position of a specified input

value (the search "key") within an array sorted by key value.[1][2] In each step, the algorithm

compares the search key value with the key value of the middle element of the array. If the

keys match, then a matching element has been found and its index, or position, is returned.

Otherwise, if the search key is less than the middle element's key, then the algorithm repeats

its action on the sub-array to the left of the middle element or, if the search key is greater, on

the sub-array to the right. If the remaining array to be searched is empty, then the key cannot

be found in the array and a special "not found" indication is returned..

Input: Enter List data and Key value to search

Output: Returns the index value of the mached element.

H/W & S/W Specifications:

Pentium –IV

Putty software

Linux Server with c compiler

Source Code:

#include<stdio.h>#include<conio.h>void lsearch(int a[],int n,int ele);void bsearch(int a[],int n,int ele);void ssort(int a[],int n);void read(int a[],int n);

void main()

8

Page 9: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

{int a[50],n,op,ele;clrscr();printf("\nMENU");printf("\n1.LINEAR SEARCH");printf("\n2. BINARY SEARCH");printf("\n3.EXIT");printf("\nEnter your option:");scanf("%d",&op);if(op>0&&op<3){printf("\nEnter the size of array:");scanf("%d",&n);read(a,n);printf("\nEnter the elements to search:");scanf("%d",&ele);}switch(op){case 1:

lsearch(a,n,ele);break;

case 2:bsearch(a,n,ele);break;

case 3:exit(0);default:printf("\nINVALID OPTION!!!");}getch();}void read(int a[],int n){int i;printf("\nEnter the %d elements below\n",n);for(i=0;i<n;i++)scanf("%d",&a[i]);}void ssort(int a[],int n){int i,j,temp;for(i=0;i<n-1;i++){for(j=i+1;j<n;j++)if(a[i]>a[j]){temp=a[i];a[i]=a[j];a[j]=temp;}}}

void lsearch(int a[],int n,int ele)

9

Page 10: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

{int flag=0,i;for(i=0;i<n;i++){if(a[i]==ele){flag=1;break;}}if(flag==1)printf("\nElement in the list");elseprintf("\nElement not in the list");}void bsearch(int a[],int n,int ele){int ll=0,ul=n-1,mid;ssort(a,n);while(ll<=ul){mid=(ll+ul)/2;if(a[mid]==ele){printf("\nElement found");break;}else if(a[mid]>ele)ul=mid-1;else if(a[mid]<ele)ll=mid+1; } if(ul>ll)printf("\nElement is not in the list");}

Result:Linear & Binary Searching techniques implemented & tested with sample data.

Date: Signature of Instructor

Review Questions

1. Differentiate b/w Linear & Binary Search?2. Compute the time complexity for Binary Search?3. Name some applications where searching techniques are useful?4. For Large volumes of data which one is more optimal?

10

Page 11: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

PROJECT NO : 3

SORTING

Learning Objectives:

To learn about:

Insertion Sort

Shell Sort

Problem Description:

Sorting is the process of making a sorted order for given unsorted List of elements.Here we

are consider two popular methods.

Insertion sort iterates, consuming one input element each repetition, and growing a sorted

output list. On a repetition, insertion sort removes one element from the input data, finds the

location it belongs within the sorted list, and inserts it there. It repeats until no input elements

remain.

Sorting is typically done in-place, by iterating up the array, growing the sorted list behind it.

At each array-position, it checks the value there against the largest value in the sorted list

(which happens to be next to it, in the previous array-position checked). If larger, it leaves the

element in place and moves to the next. If smaller, it finds the correct position within the

sorted list, shifts all the larger values up to make a space, and inserts into that correct position.

The resulting array after k iterations has the property where the first k + 1 entries are sorted

("+1" because the first entry is skipped). In each iteration the first remaining entry of the input

is removed, and inserted into the result at the correct position, thus extending the result:

becomes

with each element greater than x copied to the right as it is compared against x.

Shellsort is a generalization of insertion sort that allows the exchange of items that are far

apart. The idea is to arrange the list of elements so that, starting anywhere, considering every

hth element gives a sorted list. Such a list is said to be h-sorted. Equivalently, it can be

thought of as h interleaved lists, each individually sorted.[3] Beginning with large values of h,

this rearrangement allows elements to move long distances in the original list, reducing large

11

Page 12: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

amounts of disorder quickly, and leaving less work for smaller h-sort steps to do.[4] If the file

is then k-sorted for some smaller integer k, then the file remains h-sorted. Following this idea

for a decreasing sequence of h values ending in 1 is guaranteed to leave a sorted list in the

end.

Input: Enter unsorted List of data.

Output: Returns Sorted List.

H/W & S/W Specifications:

Pentium –IV

Putty software

Linux Server with c compiler

Source Code:

#include<stdio.h>#include<conio.h>void print(int a[],int n);void insertion(int a[],int n);void shell(int a[],int n);void bucket(int a[],int n);void main() { int n,a[30],op,i; char ch; while(1) {

clrscr();printf("\nMENU\n1.INSERTION SORT\n2.SHELL SORT\n4.EXIT\n");printf("\nENTER YOUR CHOICE: ");scanf("%d",&op); if(op >0 && op<4) { printf("\n\n Enter the number of elements:"); scanf("%d",&n); printf("\n\n Enter the elements:"); for(i=0;i<n;++i)

scanf("%d",&a[i]); }

switch(op) { case 1:insertion(a,n);print(a,n);

break; case 2:shell(a,n);print(a,n);

break; case 4:exit(0); default:printf("\n invalid choice!"); }

12

Page 13: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

printf("\n do you wish to continue(Y/N): "); flushall(); ch=getchar(); if(ch=='n'|| ch=='N') break; } getch(); }

void print(int a[],int n){int i;printf("\n the sorted list is : ");for(i=0;i<n;i++){printf("\n\t %d ",a[i]);}}void insertion(int a[],int n) { int k,i,y; for(k=1;k<n;++k) {

y=a[k];for(i=k-1;i>=0 &&y<a[i];--i) { a[i+1]=a[i]; a[i]=y; }

} }void shell(int a[],int n) { int gap,i,temp,j; for(gap=n/2;gap>0;gap/=2) { for(i=gap;i<n;++i)

{ temp=a[i]; for(j=i;j>=gap;j-=gap) if(temp<a[j-gap])

a[j]=a[j-gap]; else

break; a[j]=temp; }

} }

Result:

13

Page 14: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

Insertion, Shell Sorting Techniques were implemented & tested with sample data.

Date: Signature of Instructor

Review Questions

1. Compute the time complexity for all the three?2. Compare & contrast them based on the runtime complexity?3. For Large volumes of data which sorting is more optimal?

PROJECT NO : 4

14

Page 15: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

SORTING WITH DEVIDE AND CONQUER METHODSTRATEGY

Learning Objectives:

To learn about:

Merge Sort

Quick Sort

Problem Description:

Sorting is the process of making a sorted order for given List of elements. Here we are

consider two popular methods that are solved with devide and conquer method.

Conceptually, a Merge sort works as follows Divide the unsorted list into n sublists, each

containing 1 element (a list of 1 element is considered sorted). Repeatedly merge sublists to

produce new sublists until there is only 1 sublist remaining. This will be the sorted list.

Quicksort is a divide and conquer algorithm. Quicksort first divides a large list into two

smaller sub-lists: the low elements and the high elements. Quicksort can then recursively sort

the sub-lists.

The steps are:

1. Pick an element, called a pivot, from the list.

2. Reorder the list so that all elements with values less than the pivot come before the

pivot, while all elements with values greater than the pivot come after it (equal values

can go either way). After this partitioning, the pivot is in its final position. This is

called the partition operation.

3. Recursively apply the above steps to the sub-list of elements with smaller values and

separately the sub-list of elements with greater values.

The base case of the recursion are lists of size zero or one, which never need to be sorted.

Input: Enter unsorted List of data.

Output: Returns Sorted List.

H/W & S/W Specifications:

15

Page 16: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

Pentium –IV

Putty software

Linux Server with c compiler

Source Code:

#include<stdio.h>#include<conio.h>void quick(int a[40],int lb,int ub);int partition(int a[40],int lb,int ub);void merge(int a[40],int *temp,int ipos,int rpos,int rightend);void msort(int a[40],int *temp,int lb,int rb);void mergesort(int a[40],int n);void print(int s[40],int n);int a[40],lb,ub;void main(){int i,n,op;char ch;{clrscr();printf("MENU");printf("\n1.QUICK SORT");printf("\n2.MERGE SORT");printf("\n3.EXIT");printf("\nEnter your choice:");scanf("%d",&op);if(op>0&&op<3){printf("\nEnter the number of elements:");scanf("%d",&n);printf("\nEnter the %d elements below\n",n);for(i=0;i<n;i++){scanf("%d",&a[i]);}}switch(op){case 1: i=0;

quick(a,i,n-1);print(a,n);break;

case 2: mergesort(a,n);print(a,n);break;

case 3: exit(0);default: printf("\nInvalid Choice!!");}}getch();}void print(int a[40],int n){

16

Page 17: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

int i;printf("\nThe sorted elements are");for(i=0;i<n;i++)printf("\t%d",a[i]);}void quick(int a[40],int lb,int ub){int j;if(lb>=ub)return;j=partition(a,lb,ub);quick(a,lb,j-1);quick(a,j+1,ub);}int partition(int a[40],int lb,int ub){int x,down,temp,up;down=lb+1;up=ub;x=a[lb];while(down<=up){while(a[down]<=x)down++;while(a[up]>x)up--;if(down<up){temp=a[up];a[up]=a[down];a[down]=temp;}}temp=a[lb];a[lb]=a[up];a[up]=temp;return(up);}void mergesort(int a[40],int n){int *temp;temp=(int *)malloc(sizeof(int )*n);if(temp=='\0')printf("No space available!");else{msort(a,temp,0,n-1);free(temp);}}

void msort(int a[40],int *temp,int lb,int rb){

17

Page 18: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

int mid;if(lb<rb){mid=(lb+rb)/2;msort(a,temp,lb,mid);msort(a,temp,mid+1,rb);merge(a,temp,lb,mid+1,rb);}}void merge(int a[40],int *temp,int ipos,int rpos,int rightend){int i, leftend,n,tmppos;leftend=rpos-1;tmppos=ipos;n=rightend-ipos+1;while(ipos<=leftend&&rpos<=rightend){if(a[ipos]<=a[rpos])temp[tmppos++]=a[ipos++];elsetemp[tmppos++]=a[rpos++];}while(a[ipos]<=a[leftend])temp[tmppos++]=a[ipos++];while(a[rpos]<=a[rightend])temp[tmppos++]=a[rpos++];for(i=0;i<n;i++,rightend--)a[rightend]=temp[rightend];}

Result:

Merge & Quick Sorting Techniques were implemented & tested with sample data.

Date: Signature of Instructor

Review Questions

1. Compute time complexity for both divide & conquer sorting technique.?2. Compare both sorting techniques?3. Why is Quick Sort better than Merge sort?4. When to use quick & merge sort effectively?

PROJECT NO: 5

18

Page 19: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

STACKS

Learning Objectives:

To learn about:

Stack Data Structures

Operations on Stacks

Problem Description:

A stack is a particular kind of abstract data type or collection in which the principal (or only) operations on the collection are the addition of an entity to the collection, known as push and removal of an entity, known as pop.[1] The relation between the push and pop operations is such that the stack is a Last-In-First-Out (LIFO) data structure. In a LIFO data structure, the last element added to the structure must be the first one to be removed. This is equivalent to the requirement that, considered as a linear data structure, or more abstractly a sequential collection, the push and pop operations occur only at one end of the structure, referred to as the top of the stack. Often a peek or top operation is also implemented, returning the value of the top element without removing it.

Input: Push Data into the stack.

Output:.Performing pushing and poping the elements in the stack, we can see each and

every status of stack before and after.

H/W & S/W Specifications:

Pentium –IV

Putty software

Linux Server with c compiler

Source Code:

Stack:

#include<stdio.h>#include<conio.h>#define size 5int s[22],i;int tos=0;void push(int);int pop();void display();

void main(){int ch,ele;

19

Page 20: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

clrscr();do{printf("\nMENU");printf("\n1.TO PUSH ELEMENT");printf("\n2.TO POP ELEMENT");printf("\n3.TO DISPLAY ELEMENT");printf("\n4.EXIT");printf("\nEnter your choice");scanf("%d",&ch);switch(ch){case 1:

if(tos==size){printf("\nStack is full");}else{

printf("\nEnter element to push");scanf("%d",&ele);push(ele);printf("\nElement inserted in stack are");for(i=0;i<tos;i++){printf("\n%d\n",s[i]);}}break;

case 2:if(tos==NULL)printf("\nStack is empty");else{ele=pop();printf("\nthe poped element is %d",ele);for(i=0;i<tos;i++){printf("\n%d\n",s[i]);}}break;

case 3:display();break;

case 4:exit(0);

default: printf("\nWrong option!!");}}while(1);}void push(int ele)

20

Page 21: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

{s[tos]=ele;tos++;}

int pop(){tos--;return(s[tos]);}

void display(){int i;if(tos==NULL)printf("\nStack is empty");else{for(i=0;i<tos;i++)printf("\n%d\t",s[i]);}}

Result:

Stack Data Structures are implemented & Operations over the data structures are verified with test data.

Date: Signature of Instructor

Review Questions

1. Name any 3 applications of stacks?

2. Is there any other data structure that has LIFO Policy?

3. How do you implement 2 stacks using only one array. Your stack routines should not

indicate an overflow unless every slot in the array is used?

4. Show that it is possible to obtain the permutation P1P2.........Pn from 1,2,.........n using

a stack if and only if there are no indices i < j < k such that Pj < Pk < Pi.

QUEUES

Learning Objectives:

21

Page 22: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

To learn about:

Queue Data Structures

Operations on Queues

Problem Description:

A queue is a particular kind of abstract data type or collection in which the principal (or only) operations on the collection are the addition of an entity to the collection, known as enqueue and removal of an entity, known as dequeue. The relation between the enqueue and dequeue operations is such that the queue is a First-In-First-Out (FIFO) data structure. In a FIFO data structure, the First element added to the structure must be the first one to be removed. This is equivalent to the requirement that, considered as a linear data structure, or more abstractly a sequential collection, the dequeue and enqueue operations occur at front and rear ends of the structure. Returning the value of the dequeue element without removing it.

Input: Inserting and removing Data into the queue.

Output:.Performing enqueue and dequeue the elements in the queue, we can see each and

every status of queue before and after.

H/W & S/W Specifications:

Pentium –IV

Putty software

Linux Server with c compiler

Source Code:

Queue:

#include<stdio.h>#include<conio.h>#define size 7int a[22],i,front=-1,rear=0;void insert(int ele);int delete();void display();void main(){int op,ele,i;clrscr();do{printf("\nMENU");printf("\n1.INSERTION");printf("\n2.DELETION");printf("\n3.DISPLAY");printf("\n4.EXIT");printf("\nEnter your option:");scanf("%d",&op);

22

Page 23: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

switch(op){case 1:

if(rear==size-1){ printf("\nQUEUE FULL"); }else{printf("\nEnter the element to be insert:");scanf("%d",&ele);insert(ele);printf("\nElement inserted");printf("\nElements after insertion are");for(i=0;i<rear;i++){ printf("\n%d",a[i]);}

} break;case 2:

if(front==-1){ printf("\nQUEUE EMPTY"); }else{ele=delete();printf("\nElements after deletion are");for(i=front;i<rear;i++){ printf("\n%d",a[i]); }}break;

case 3:display();break;

case 4: exit(0);default:printf("\nInvalid Choice");}}while(1);}void insert(int ele){a[rear]=ele;rear++;if(front==-1)front=0;}int delete(){int t;t=a[front];if(front==(rear-1)){front=-1;rear=0;}elsefront++;return(0);}

23

Page 24: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

void display(){ int i;if(rear==0) printf("\nQUEUE EMPTY");else{ for(i=front;i<rear;i++){ printf("%d\t",a[i]);}}

Result:Queue Data Structures are implemented & Operations over the data structures are verified with test data.

Date: Signature of Instructor

Review Questions

1. Name any 3 applications of queues?

2. Is there any other data structure that has FIFO Policy?

EXERCISE NO : 6

APPLICATIONS OF STACKS

24

Page 25: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

Learning Objectives:

To learn about:

Applications of Stacks

Various ways of representing expressions & their conversions from one

form to the other.

Evaluating postfix expression

Problem Description:

Various ways of representing expressions & their conversions from one form to the other is possible with Stacks. The following process explains how this conversion and evaluation can be implemented with stacks.

Conversion While there are tokens to be read:

Read a token. If the token is a number, then add it to the output queue. Else if the token is an operator, o1, then:

1) while there is an operator, o2, at the top of the stack, and either o1 is associative or left-associative, and its precedence is less than or equal to that of o2, or o1 is right-associative and its precedence is less than that of o2, pop o2 off the stack, onto the output queue; 2) push o1 onto the operator stack.

Else if the token is a left parenthesis, then push it onto the stack. Else if the token is a right parenthesis, then pop operators off the stack, onto

the output queue, until the token at the top of the stack is a left parenthesis, at which point it is popped off the stack but not added to the output queue. If the stack runs out without finding a left parenthesis, then there are mismatched parentheses.

When there are no more tokens to read, pop all the operators, if any, off the stack, add each to the output as it is popped out and exit. (These must only be operators; if a left parenthesis is popped, then there are mismatched parentheses.)

Postfix EvaluationIn normal algebra we use the infix notation like a+b*c. The corresponding postfix notation is abc*+. The algorithm for the conversion is as follows :

Scan the Postfix string from left to right. Initialise an empty stack. If the scannned character is an operand, add it to the stack. If the scanned

character is an operator, there will be atleast two operands in the stack. If the scanned character is an Operator, then we store the top most

element of the stack (top Stack) in a variable temp. Pop the stack. Now

25

Page 26: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

evaluate topStack(Operator)temp. Let the result of this operation be retVal. Pop the stack and Push retVal into the stack.

Repeat this step till all the characters are scanned.

After all characters are scanned, we will have only one element in the stack. Return topStack.

Input: Providing infix expression and providing postfix expression

Output: Corresponding postfix expression to be display for the given input expression and

postfix evaluation.

H/W & S/W Specifications:

Pentium –IV

Putty software

Linux Server with c compiler

Source Code:

Program to convert an infix to postfix expression

#include<stdio.h>#include<conio.h>#include<math.h>#define n 10int issymbol(char x);void infixtopost(char ine[],char pe[]);int isopen(char x);int isoperator(char x);int precedence(char x);char top(char[] );int pop(char s[]);void push(char s[],int x);int tos;char ine[50],pe[50];void main(){ int i=0; clrscr(); printf("enter infix expression:"); gets(ine);

while((ine[i]!='\0')) { infixtopost(ine,pe); ++i; } printf("postfix expression is\n"); for(i=0;pe[i]!='\0';++i) printf("%c",pe[i]); getch();

26

Page 27: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

}

void infixtopost(char ine[],char pe[]) { int i,j,px,py; char x,y,s[20]; tos=-1; i=j=0; while(ine[i]!='\0') { x=ine[i]; if(!isoperator(x)&&!issymbol(x))

pe[j++]=x; else if(isoperator(x)) {

if(tos!=-1) { y=top(s); if(!issymbol(y))

{ py=precedence(y); px=precedence(x); while(tos!=-1&&px<=py) { pe[j++]=pop(s); y=pop(s); py=precedence(y); }

} } push(s,x); } else {

if(isopen(x)) push(s,x); else { while(top(s)!='(')

pe[j++]=pop(s); pop(s);

} } ++i;

} } int issymbol(char x) { if((x=='(')||(x==')'))

return(1); else

return(0); }

27

Page 28: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

int isopen(char x) { if(x=='(')

return(1); else

return(0); } int isoperator(char x) {

if(x=='*'||x=='+'||x=='-'||x=='/'||x=='%') return(1);

else return(0);

} int precedence(char x) { if(x=='^')

return(3); else if(x=='%'||x=='*'||x=='/')

return(2); else

return(0); } char top(char s[]) { if(tos>-1)

return(s[tos]); else

return(-1); } int pop(char s[]) { int y; if(tos<=-1)

printf("under flow\n"); else {

y=s[tos]; tos--;

} return(y); } void push(char s[],int x) { if(tos>=n-1)

printf("over flow\n"); else {

tos++; s[tos]=x;

} return;}

28

Page 29: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

A program to evaluate the postfix expression.

#include<stdio.h>#include<conio.h>int tos,n;int postfixvalue(char pe[]);int isoperator(char x);int pop(int s[50]);void push(int s[50],int);void main(){ char pe[50]; int i=0,p; clrscr(); printf("enter the post fix expression:\n"); while(1) { scanf("%c",&pe[i]); if(pe[i]=='#')

break; ++i;

} p=postfixvalue(pe); printf("The value of post fix expression is %d\n",p); getch();}int postfixvalue(char pe[]){ int i,x,y,z,s[50]; tos=-1; i=0; while(pe[i]!='#') { if(isoperator(pe[i])) {

y=pop(s); x=pop(s); switch(pe[i]) { case '*': z=x*y;

break; case '+':z=x+y;

break; case '-':z=x-y;

break; case '/':z=x/y;

break; case '%':z=x%y;

break; } push(s,z);

} else {

29

Page 30: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

printf("enter the value of %c:",pe[i]);scanf("%d",&x);push(s,x);

} ++i; } return(s[tos]); }

void push(int s[],int x){ if(tos>=50) printf("over flow\n"); else { tos++; s[tos]=x; } return;}int pop(int s[]){ int y; if(tos<=-1) { printf("stack is empty:\n"); return(-1); } else { y=s[tos]; tos--; } return(y); }

int isoperator(char x) { if(x=='*'||x=='%'||x=='/'||x=='+'||x=='-') return(1); else

return(0); }Result:

program implemented for conversion of an infix expression to postfix expression & to

evaluate it & is tested with sample data.

Date: Signature of Instructor

Review Questions

30

Page 31: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

1. Name the applications where we make use of these kind of conversions?2. Convert the following infix expression to postfix expression?

(((a+b) * (c+d))/(f+g/k))3. Evaluate the following postfix expression.

456*78/3-4+95*

PROJECT NO : 7

SINGLE LINKED LIST

Learning Objectives:

To learn about:

Single linked list

31

Page 32: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

Insertion, deletion operations of SLL.

Merging , Reversing a SLL.

Problem Description:

In a linked list a data structure consisting of a group of nodes which together represent a

sequence. Under the simplest form, each node is composed of a datum and a reference (in

other words, a link) to the next node in the sequence; more complex variants add additional

links. This structure allows for efficient insertion or removal of elements from any position in

the sequence.

Input: Inserting and removing Data in Single Linked List.

Output:.Performing insertion, deletion, merging and reversing the elements in the Single

Linked List and shows status of SLL before and after.

H/W & S/W Specifications:

Pentium –IV

Putty software

Linux Server with c compiler

Source Code:

#include<stdio.h>#include<conio.h>struct node{ int data; struct node *next;};typedef struct node node;node *head1,*temp,*head2,*head3,*newnode;void create(node *);void display(node *);node *insertion(node *);node *Delete(node *);node *merge();node *sort(node *);void main(){ int choice; char ch; while(1) { clrscr();

32

Page 33: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

printf("\n\t\t\tMENU\n\t\t1.create\n\t\t2.insertion\n\t\t3.deletion\n\t\t4.merging\n\t\t5.sorting\n\t\t6.exit"); printf("\n\t\tenter any choice: "); scanf("%d",&choice); if(choice>0&&choice<6)

head1=(node *)malloc(sizeof(node)); switch(choice) {

case 1: create(head1); display(head1); break;

case 2: create(head1); head1=insertion(head1); display(head1); break;

case 3: create(head1); head1=Delete(head1); display(head1); break;

case 4: create(head1); head2=(node *)malloc(sizeof(node)); printf("\n enter data values of other list:\n"); create(head2); head3=merge(); display(head3); break;

case 5: create(head1); head1=sort(head1); display(head1); break;

case 6: exit(0); default: printf("\n\t Invalid choice! \n");

} printf("\n do you wish to continue(Y/N): "); flushall(); ch=getchar(); if(ch=='N'||ch=='n')

break; } getch();

}

void create(node *head) { printf("enter data(Enter 0 to stop):"); scanf("%d",&head->data); if(head->data==0) {

head->next=NULL; return;

} else

33

Page 34: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

{ head->next=(node *)malloc(sizeof(node)); create(head->next);

} }

void display(node *head) { if(head->next==NULL) {

return; } else { if(head->data==0)

return; printf("\n\t%d",head->data); display(head->next);}

}

node * insertion(node *head) { int pos,choice,count=0; printf(" specify where the insertion is to be made: "); printf("\n\t1.beginning\n\t2.any position\n\t3.end"); printf("\n enter your specification: "); scanf("%d",&choice); if(choice>0&&choice<4) {

newnode=(node *)malloc(sizeof(node)); printf("\n enter data to be inserted: "); scanf("%d",&newnode->data);

} if(choice==1) {

newnode->next=head; head=newnode;

} else if(choice==2)

{ printf("\n enter the position of insertion : "); scanf("%d", &pos); temp=head; while(count<pos-2) {

temp=temp->next; count++;

}newnode->next=temp->next;temp->next=newnode;

}

34

Page 35: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

else if(choice==3) { temp=head; while(temp->next!=NULL)

{ temp=temp->next; } temp->next=newnode; newnode->next=NULL;

} return(head); } node * Delete(struct node *head) { int pos,choice,count =0; printf(" specify where the deletion is to be made:\n\t1.begining\n\t2.any position\n\t3.end"); printf("\n enter your specification: "); scanf("%d",&choice); if(choice==1) { head=head->next;

} else if(choice==2)

{ printf("\n enter position of deletion: "); scanf("%d",&pos); temp=head; while(count<pos-2)

{ temp=temp->next; count++; } temp->next=temp->next->next;

} else if(choice==3)

{ temp=head; while(temp->next->next!=NULL)

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

}return(head);

}

node *merge(void) { node *temp1,*temp2,*temp3; temp1=head1; temp2=head2;

35

Page 36: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

temp3=(node *)malloc(sizeof(node)); head3=temp3; while((temp1!=NULL)&&(temp2!=NULL))

{ if(temp1->data<temp2->data)

{ temp3->data=temp1->data; temp1=temp1->next;}

else { temp3->data=temp2->data; temp2=temp2->next; }

temp3->next=(node *)malloc(sizeof(node)); temp3=temp3->next; } if(temp1!=NULL)

temp3->next=temp2; else if(temp2!=NULL)

temp3->next=temp1; temp3->data=0; temp3->next=NULL; return(head3);

} node * sort(node *head) { int p; node *t1,*t2; t1=head; for(;t1!=NULL;t1=t1->next)

for(t2=t1->next;t2!=NULL;t2=t2->next) { if(t1->data<t2->data)

{ p=t1->data; t1->data=t2->data; t2->data=p; }

} return(head);

}Result:

Operations on single linked list were performed & tested with sample data.

Date: Signature of Instructor

Review Questions

36

Page 37: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

1. Can the dynamic-set operation INSERT be implemented on a singly linked list in

O(1) time? What about DELETE?

2. Implement the dictionary operations INSERT,DELETE and SEARCH using singly

linked,circular lists. What are the running times of the procedures?

EXERCISE NO : 8

DOUBLE LINKED LIST

Learning Objectives:

To learn about:

Double Linked List

37

Page 38: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

Operations on DLL.

Problem Description:

In a doubly-linked list is a linked data structure that consists of a set of sequentially linked records called nodes. Each node contains two fields, called links, that are references to the previous and to the next node in the sequence of nodes. The beginning and ending nodes' previous and next links, respectively, point to some kind of terminator, typically a sentinel node or null, to facilitate traversal of the list. If there is only one sentinel node, then the list is circularly linked via the sentinel node. It can be conceptualized as two singly linked lists formed from the same data items, but in opposite sequential orders.

The two node links allow traversal of the list in either direction. While adding or removing a node in a doubly-linked list requires changing more links than the same operations on a singly linked list, the operations are simpler and potentially more efficient (for nodes other than first nodes) because there is no need to keep track of the previous node during traversal or no need to traverse the list to find the previous node, so that its link can be modified.

Input: inserting and removing Data in Doubly Linked List.

Output:.Performing insertion, deletion, merging and reversing the elements in the Doubly

Linked List and shows status of DLL before and after.

H/W & S/W Specifications:

Pentium –IV

Putty software

Linux Server with c compiler

Source Code:

#include<stdio.h>#include<conio.h>struct node{int data;struct node *prev;struct node *next;}*head1,*head2,*temp,*head,*temp1,*temp2,*newnode;void create();

38

Page 39: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

void insert(int n);void Delete(int n);void sort();void merge();void reverse();void search();void display();void main(){int n,op;clrscr();do{printf("\nMENU");printf("\n1.insertion");printf("\n2.deletion");printf("\n3.sorting");printf("\n4.merging");printf("\n5.reversing");printf("\n6.searching");printf("\n7.exit");printf("\nenter your option");scanf("%d",&op);if(op>0&&op<7){printf("\nenter elements in list");create();head1=head;}switch(op){case 1: insert(n); display(); break;case 2: Delete(n); display(); break;case 3: sort(); display(); break;case 4: merge(); display(); break;case 5:

reverse();

break;case 6:

search();break;

39

Page 40: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

case 7: exit(0);default:

printf("\ninvalid option");}}while(1);}void create(){int x,n=1;head=(struct node *)malloc(sizeof(struct node));printf("\nenter data");scanf("%d",&x);head->data=x;head->next=NULL;temp=head;while(x!=0){newnode=(struct node *)malloc(sizeof(struct node));printf("\nenter data");scanf("%d",&x);if(x!=0){newnode->prev=temp;newnode->data=x;newnode->next=NULL;temp->next=newnode;temp=newnode;++n;}elsebreak;}}void insert(int n){int pos,x,i;printf("\nenter position to insert");scanf("%d",&pos);printf("\nenter element to insert");scanf("%d",&x);newnode=(struct node *)malloc(sizeof(struct node));if(pos==1){newnode->data=x;newnode->prev=NULL;newnode->next=head;head=newnode;}else if(pos==n-1){temp=head;while(temp->next!=NULL)temp=temp->next;

40

Page 41: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

newnode->data=x;newnode->next=NULL;newnode->prev=temp;temp->next=newnode;temp=newnode;}else{temp=head;for(i=1;i<pos-1;++i)temp=temp->next;newnode->data=x;newnode->next=temp->next;temp->next->prev=newnode;temp->next=newnode;newnode->prev=temp;}}void Delete(int n){int pos,i;printf("\nenter position to delete");scanf("%d",&pos);if(pos==1){head=head->next;head->prev=NULL;}else if(pos==n-1){temp=head;while(temp->next!=NULL)temp=temp->next;temp->prev->next=NULL;}else{temp=head;for(i=1;i<pos;++i)temp=temp->next;temp->prev->next=temp->next;temp->next->prev=temp->prev;}}void sort(){int t;for(temp1=head;temp1!=NULL;temp1=temp1->next)for(temp2=head;temp2->next!=NULL;temp2=temp2->next){if((temp1->data)<(temp2->data)){t=temp1->data;temp1->data=temp2->data;

41

Page 42: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

temp2->data=t;}}}void merge(){printf("\ncreate another list");create();temp=head;while(temp->next!=NULL)temp=temp->next;temp->next=head1;}void reverse(){ temp=head; while(temp->next!=NULL) temp=temp->next; while(temp!=NULL) { printf("\n%d",temp->data); temp=temp->prev; }}void search(){int ele,flag=0;printf("\nenter element to search");scanf("%d",&ele);for(temp=head;temp!=NULL;temp=temp->next){if((temp->data)==ele){flag=1;break;}}if(flag==1)printf("\n%d is in list",ele);elseprintf("\n%d is not in list",ele);}void display(){temp=head;printf("\nelements in list are:");while(temp!=NULL){printf("\n%d",temp->data);temp=temp->next;}}

42

Page 43: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

Result:

Operations on Double linked list were performed & tested with sample data.

Date: Signature of Instructor

Review Questions

1. List the applications of DLL’s.

2. How to reverse a DLL with out using previous pointer?

PROJECT NO :9

POLYNOMIAL

Learning Objectives:

To learn about:

43

Page 44: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

Polynomial manipulations

How to Apply Linked List.

Problem Description:

The biggest integer that we can store in a variable of the type int is 231 - 1 on 32-but CPU. You can easily verify this by the following operations:

int prod=1;for(int i = 1; i <=; 31; i ++) prod *= 2;System.out.println(prod);

This code doesn't produce an error, it produces a result! The printed value is a negative integer -2147483648 = -231. If the value becomes too large, Java saves only the low order 32 (or 64 for longs) bits and throws the rest away.

In real life applications we need to deal with integers that are larger than 64 bits (the size of a long). To manipulate with such big numbers, we will be using a linked list data structure. First we observe that each integer can be expressed in the decimal system of notation.

937 = 9*102 + 3*101 + 7*100 2011 = 2*103 + 0*102 + 1*101 + 1*100

Now, if we replace a decimal base 10 by a character, say 'x', we obtain a univariate polynomial, such as

0.45 - 1.89 x2 + 3.4 x5 + 9 x16

We will write an application that manipulates polynomials in one variable with real coefficients.Among many operations on polynomials, we implement addition, multiplication, differentiation and evaluation. A polynomial willbe represented as a linked list, where each node has an integer degree, a double coefficient and a reference to the next term. The final node will have a null reference to indicate the end of the list. Here is a linked link representation for the above polynomial:

Input: Enter polynomial Data.

Output:Shows resultant polynomial expression after summing and multiplication.

H/W & S/W Specifications:Pentium –IV

Putty software

Linux Server with c compiler

Source Code:#include<stdio.h>#include<conio.h>

44

Page 45: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

#include<process.h>struct term{

float coef;int xp;struct term *next;

};typedef struct term *tptr;tptr createheader();tptr findpos(tptr p,int e);tptr findprev(tptr p,int e);tptr find(tptr p,int e);void insertterm(tptr p,int e,float c);void deleteterm(tptr p,int e);tptr sumpoly(tptr p1,tptr p2);tptr propoly(tptr p1,tptr p2);void display(tptr p);void main(){

tptr p,p2,res;int e,op;float c;char ch;p=createheader();clrscr();printf("\nEnter the coefeicient,xpower:");while(1){

scanf("%f%d",&c,&e);insertterm(p,e,c);if(e==0)break;

}display(p);while(1){

printf("\n\n\tMENU");printf("\n\n1.FIND");printf("\n\n2.INSERT");printf("\n\n3.DELETE");printf("\n\n4.ADDITION");printf("\n\n5.MULTIPLICATION");printf("\n\n6.EXIT");printf("\nEnter your option:");scanf("%d",&op);switch(op){case 1:

printf("\nEnter the exponent to be found");scanf("%d",&e);res=find(p,e);if(res==NULL)printf("\nThe power doesnot exist");else

45

Page 46: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

{printf("%f*x^%d",res->next->coef,e);

}break;

case 2:printf("\nEnter the coefficient and xpower");scanf("%f%d",&c,&e);insertterm(p,e,c);display(p);break;

case 3:printf("\nEnter the xpower to be deleted");scanf("%d",&e);deleteterm(p,e);display(p);break;

case 4:p2=createheader();printf("\nEnter the terms in the second poly");while(1){

scanf("%f%d",&c,&e);insertterm(p2,e,c);if(e==0)break;

}res=sumpoly(p,p2);display(res);break;

case 5:p2=createheader();printf("\nEnter the terms in the second poly");while(1){

scanf("%f%d",&c,&e);insertterm(p2,e,c);if(e==0)break;

}res=propoly(p,p2);display(res);break;

case 6:exit(0);

default:printf("\nInvalid choice");}printf("\nDo you wish to continue(y/n)");flushall();scanf("%c",&ch);if(ch=='n'||ch=='N')break;

}}tptr createheader()

46

Page 47: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

{tptr p;p=(tptr)malloc(sizeof(struct term));if(p!=NULL)p->next=NULL;else{printf("\nOut ofspace");exit(0);}return(p);

}tptr find(tptr p,int e){

tptr temp;temp=p;while(temp!=NULL){if(temp->next->xp==e)return(temp);temp=temp->next;}return(NULL);

}tptr findpos(tptr p,int e){

tptr temp;temp=p;while((temp->next!=NULL)&&(temp->next->xp>e))temp=temp->next;return(temp);

}void insertterm(tptr p,int e,float c){

tptr pos,temp;if(p->next==NULL){

temp=(tptr)malloc(sizeof(struct term));temp->coef=c;temp->xp=e;p->next=temp;temp->next=NULL;

}else{pos=find(p,e);if(pos!=NULL)pos->next->coef+=c;else{ temp=(tptr)malloc(sizeof(struct term)); temp->coef=c; temp->xp=e; pos=findpos(p,e); temp->next=pos->next;

47

Page 48: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

pos->next=temp;}}

}void deleteterm(tptr p,int e){

tptr pos,temp;pos=find(p,e);if(pos!=NULL){

temp=pos->next;pos->next=pos->next->next;free(temp);

}elseprintf("\nThe power not found");

}tptr sumpoly(tptr p1,tptr p2){

tptr t1,t2,p3;float c;p3=createheader();t1=p1->next;t2=p2->next;while((t1!=NULL)&&(t2!=NULL)){

if(t1->xp<t2->xp){

insertterm(p3,t2->xp,t2->coef);t2=t2->next;

}else if(t1->xp>t2->xp){

insertterm(p3,t1->xp,t1->coef);t1=t1->next;

}else{

c=t1->coef+t2->coef;insertterm(p3,t1->xp,c);t1=t1->next;t2=t2->next;

}}while(t1!=NULL){

insertterm(p3,t1->xp,t1->coef);t1=t1->next;

}while(t2!=NULL){

insertterm(p3,t2->xp,t2->coef);t2=t2->next;

}

48

Page 49: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

return(p3);}tptr propoly(tptr p1,tptr p2){

tptr t1,t2,p3;int e;float c;t1=p1->next;t2=p2->next;while(t1!=NULL){

t2=p2->next;while(t2!=NULL){

c=t1->coef*t2->coef;e=t1->xp+t2->xp;insertterm(p3,e,c);t2=t2->next;

}t1=t1->next;

}return(p3);

}void display(tptr p){

tptr temp;temp=p->next;while(temp!=NULL){printf("%+f*x^%d",temp->coef,temp->xp);temp=temp->next;}

}Result:

Polynomial Data Structure using linked lists were implemented & their operations were tested with sample data.

Date: Signature of Instructor

Review Questions

1. How polynomials are useful in computer applications?2. Compute the addition & multiplication of the following polynomials.

5x2+4x3+9 & 7x4+5x3+10

PROJECT NO : 9

BINARY SEARCH TREE

Learning Objectives:

To learn about:

49

Page 50: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

Binary Search Tree

Inserting an element into BST

Deleting an element in to BST.

Tree traversals

Problem Description:

Binary search tree (BST), sometimes also called an ordered or sorted binary tree, is a node-based binary 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.

Input: Enter Data to construct Binary Search Tree.

Output: After performing insertion and deletion operations BST status will be displayed

H/W & S/W Specifications:Pentium –IV

Putty software

Linux Server with c compiler

Source Code:

#include<stdio.h>#include<conio.h>#include<stdlib.h>#include<alloc.h>struct tree{int data;struct tree *left,*right;};typedef struct tree node;node *tree;node *insert(node *,int);node *del(node *,int);void inorder(node *);void postorder(node *);void preorder(node *);node *finmin(node *);void main(){int ch,ele,op;clrscr();tree=NULL;do{

50

Page 51: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

clrscr();printf("\n 1.insert");printf("\n 2.delete");printf("\n 3.traversal");printf("\n 4.exit");printf("\n enter your choice:");scanf("%d",&ch);switch(ch){case 1:

printf("\n enter element to insert(or 0 to stop):");scanf("%d",&ele);while(ele!=0){tree=insert(tree,ele);scanf("%d",&ele);}getch();break;

case 2:printf("\m enter element to delete:");scanf("%d",&ele);

tree=del(tree,ele);printf("element %d deleted ",ele);getch();break;

case 3: do{printf("\n 1.preorder");printf("\n 2.inorder");printf("\n 3.postorder");printf("\n 4.exit");printf("\n enter your choice:");scanf("%d",&op);switch(op){case 1:

printf("\n preorder of tree...");preorder(tree);getch();break;

case 2:printf("\n inorder of tree...");inorder(tree);getch();break;

case 3:printf("\n postorder of tree...");postorder(tree);getch();break;

case 4: exit(0);

51

Page 52: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

}}while(1);

case 4:exit(0);

default:printf("\n invalid choice");

}}while(1);}node *insert(node *t,int ele){if(!t){t=(node *)malloc(sizeof(node));t->data=ele;t->left=NULL;t->right=NULL;return(t);}if(ele<t->data)t->left=insert(t->left,ele);if(ele>t->data)t->right=insert(t->right,ele);return(t);}void preorder(node *t){if(t){printf("%d\t",t->data);preorder(t->left);preorder(t->right);}}void inorder(node *t){if(t){inorder(t->left);printf("%d\t",t->data);inorder(t->right);}}void postorder(node *t){if(t){postorder(t->left);postorder(t->right);printf("%d\t",t->data);}}node *del(node *t,int ele){

52

Page 53: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

node *temp;if(t==NULL)printf("\n element not found");else if(ele<t->data)t->left=del(t->left,ele);else if(ele>t->data)t->right=del(t->right,ele);else if(t->left&&t->right){temp=finmin(t->right);t->data=temp->data;t->right=del(t->right,t->data);}else{temp=t;if((t->left)==NULL)t=t->right;else if((t->right)==NULL)t=t->left;free(temp);}return t;}node * finmin(node *t){if(t==NULL)return NULL;elseif(t->left==NULL)return t;elsereturn finmin(t->left);}

Result:

Binary Search Tree is implemented & tested with sample data.

Date: Signature of Instructor

Review Questions

1. A binary search tree is constructed by inserting the key values 1, 2, 3, 4, 5, 6, 7 in some order specified by a permutation of 1, ..., 7, into an initially empty tree. Which of these permutations will lead to a complete binary search tree ( 1 node at level 1, 2 nodes at level 2, and 4 nodes at level 3)?

53

Page 54: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

2. Is the operation of deletion in a binary search tree commutative in the sense that deleting x and then y from a binary search tree leaves the same tree as deleting y and then x? Argue why it is so or give a counter-example.

3. A binary search tree is constructed by inserting the key values 1, 2, 3, 4, 5, 6, 7 in some order specified by a permutation of 1... 7, into an initially empty tree. Which of these permutations will lead to a complete binary search tree ( 1 node at level 1, 2 nodes at level 2, and 4 nodes at level 3)?

PROJECT NO: 11

HASHING

Learning Objectives:

To learn about:

54

Page 55: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

Separate chaining Hashing Technique.

Problem Description:

In the method known as separate chaining, each bucket is independent, and has some sort of list of entries with the same index. The time for hash table operations is the time to find the bucket (which is constant) plus the time for the list operation. (The technique is also called open hashing or closed addressing.)

In a good hash table, each bucket has zero or one entries, and sometimes two or three, but rarely more than that. Therefore, structures that are efficient in time and space for these cases are preferred. Structures that are efficient for a fairly large number of entries are not needed or desirable. If these cases happen often, the hashing is not working well, and this needs to be fixed.

Input: Enter data for Hash table.

Output: Showing the Hash table data after performing operations.

H/W & S/W Specifications:Pentium –IV

Putty software

Linux Server with c compiler

Source Code:

#include<stdio.h>typedef struct list_node *node_ptr;struct list_node{element_type element;node_ptr next;};typedef node_ptr LIST;typedef node_ptr position;/* LIST *the_list will be an array of lists, allocated later *//* The lists will use headers, allocated later */struct hash_tbl{

unsigned int table_size;LIST *the_lists;};typedef struct hash_tbl *HASH_TABLE;

HASH_TABLEinitialize_table( unsigned int table_size ){HASH_TABLE H;int i;if( table size < MIN_TABLE_SIZE )

55

Page 56: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

{ error("Table size too small"); return NULL;}/* Allocate table */ H = (HASH_TABLE) malloc ( sizeof (struct hash_tbl) ); if( H == NULL ) fatal_error("Out of space!!!"); H->table_size = next_prime( table_size );/* Allocate list pointers */H->the_lists = (position *)malloc( sizeof (LIST) * H->table_size );if( H->the_lists == NULL )fatal_error("Out of space!!!");/* Allocate list headers */for(i=0; i<H->table_size; i++ ){

H->the_lists[i] = (LIST) malloc( sizeof (struct list_node) );if( H->the_lists[i] == NULL )fatal_error("Out of space!!!");elseH->the_lists[i]->next = NULL;}return H;}

positionfind( element_type key, HASH_TABLE H ){position p;LIST L;L = H->the_lists[ hash( key, H->table_size) ];p = L->next;while( (p != NULL) && (p->element != key) )/* Probably need strcmp!! */p = p->next;return p;}

voidinsert( element_type key, HASH_TABLE H ){position pos, new_cell;LIST L;pos = find( key, H );if( pos == NULL ){new_cell = (position) malloc(sizeof(struct list_node));if( new_cell == NULL )fatal_error("Out of space!!!");else

56

Page 57: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

{L = H->the_lists[ hash( key, H->table size ) ];new_cell->next = L->next;new_cell->element = key; /* Probably need strcpy!! */L->next = new_cell;}

}

}

Result:

Separate chaining Hashing technique was implemented & tested its performance with sample

data.

Date: Signature of Instructor

Review Questions

1. Given input {4371, 1323, 6173, 4199, 4344, 9679, 1989} and a hash function h(x) = x(mod 10), show the resulting open hash table

EXERCISE NO : 12

STACKS

Learning Objectives:

To learn about:

57

Page 58: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

Implementing Stacks & Queues using Linked lists.

Problem Description:

A stack is a particular kind of abstract data type or collection in which the principal (or only) operations on the collection are the addition of an entity to the collection, known as push and removal of an entity, known as pop.[1] The relation between the push and pop operations is such that the stack is a Last-In-First-Out (LIFO) data structure. In a LIFO data structure, the last element added to the structure must be the first one to be removed. This is equivalent to the requirement that, considered as a linear data structure, or more abstractly a sequential collection, the push and pop operations occur only at one end of the structure, referred to as the top of the stack. Often a peek or top operation is also implemented, returning the value of the top element without removing it.

Input: Push Data into the stack.

Output:.Performing pushing and poping the elements in the stack, we can see each and

every status of stack before and after.

H/W & S/W Specifications:

Pentium –IV

Putty software

Linux Server with c compiler

Source Code:

#include<stdio.h>#include<conio.h>struct stack{int data;struct stack *next;}*tos;

void create(int n);void push(int n);int pop();void display();

void main(){int op,n,t;tos=NULL;clrscr();do{printf("\n MENU\n1.PUSH\n2.POP\n3.DISPLAY\n4.EXIT");printf("\n ENter Your Option:");scanf("%d",&op);switch(op){

58

Page 59: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

case 1:printf("\n Enter Data:");scanf("%d",&n);if(tos==NULL){create(n);display();}else{push(n);display();}break;case 2:if(tos==NULL){printf("\n Stack Is Empty");}else{t=pop();printf("\n Poped Element is %d",t);display();break;}case 3:display();break;case 4:exit(0);default:printf("\n Invalid Option");}}while(1);}

void create(int n){tos=(struct stack *)malloc(sizeof(struct stack));tos->data=n;tos->next=NULL;}

void push(int n){struct stack *nn;nn=(struct stack *)malloc(sizeof(struct stack));nn->data=n;nn->next=tos;tos=nn;}

int pop(){int t;

59

Page 60: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

t=tos->data;tos=tos->next;return(t);}

void display(){struct stack *p;if(tos==NULL){printf("\n Stack Is Empty");}else{printf("\n Elements In stack are:");p=tos;while(p!=NULL){printf("\t-> %d",p->data);p=p->next; }}}

Result:

Stacks & Queue Data structures were implemented using Linked Lists & also all possible operations were tested over them with sample data.

Date: Signature of Instructor

Review Questions

1. Implement a stack using a singly linked list L. The run time of PUSH and POP should

be O(1).

QUEUES

Learning Objectives:

To learn about:

Implementing Queues using Linked lists.

60

Page 61: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

Problem Description:

A queue is a particular kind of abstract data type or collection in which the principal (or only) operations on the collection are the addition of an entity to the collection, known as enqueue and removal of an entity, known as dequeue. The relation between the enqueue and dequeue operations is such that the queue is a First-In-First-Out (FIFO) data structure. In a FIFO data structure, the First element added to the structure must be the first one to be removed. This is equivalent to the requirement that, considered as a linear data structure, or more abstractly a sequential collection, the dequeue and enqueue operations occur at front and rear ends of the structure. Returning the value of the dequeue element without removing it.

Input: Inserting and removing Data into the queue.

Output:.Performing enqueue and dequeue the elements in the queue, we can see each and

every status of queue before and after.

H/W & S/W Specifications:

Pentium –IV

Putty software

Linux Server with c compiler

Source Code:

#include<stdio.h>#include<malloc.h>#define MAXSIZE 10void insertion();void deletion();void display();struct node{

int info;struct node *link;

}*new,*temp,*p,*front=NULL,*rear=NULL;typedef struct node N;

main(){

int ch;do{printf("\n\t\t\tLinked queue");printf("\n 1.Insertion");printf("\n 2.Deletion");printf("\n 3.Display");printf("\n 4.Exit");printf("\n Enter your choice : ");scanf("%d",&ch);

61

Page 62: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

switch(ch){

case 1:insertion();

break;case 2:

deletion();break;

case 3:display();break;

default:break;

}}while(ch<=3);

}void insertion(){

int item;new=(N*)malloc(sizeof(N));printf("\nEnter the item : ");scanf("%d",&item);new->info=item;new->link=NULL;if(front==NULL)

front=new;else

rear->link=new;rear=new;

}void deletion(){

if(front==NULL)printf("\nQueue is empty");

else{

p=front;printf("\nDeleted element is : %d",p->info);front=front->link;free(p);

}}void display(){

if(front==NULL)printf("\nQueue is empty");

else{

printf("\nThe elements are : ");temp=front;while(temp!=NULL){

62

Page 63: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

printf("%d",temp->info);temp=temp->link;

}}

}

Result:

Stacks & Queue Data structures were implemented using Linked Lists & also all possible operations were tested over them with sample data.

Date: Signature of Instructor

Review Questions

1. Explain how to implement a queue using two stacks. Analyse the running time of the

queue operations.

2. Implement a queue using a singly linked list L. The run time of ENQUEUE and

DEQUE should be O(1).

EXERCISE NO : 13

AVL TREE

Learning Objectives:

To learn about:

To learn how to construct AVL Tree.

63

Page 64: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

Problem Description

AVL tree (Adelson-Velskii and Landis' tree, named after the inventors) is a self-balancing

binary search tree, and it was the first such data structure to be invented.[1] In an AVL tree, the

heights of the two child subtrees of any node differ by at most one; if at any time they differ

by more than one, rebalancing is done to restore this property. Lookup, insertion, and deletion

all take O(log n) time in both the average and worst cases, where n is the number of nodes in

the tree prior to the operation. Insertions and deletions may require the tree to be rebalanced

by one or more tree rotations.

Input: Enter data for constructing AVL Tree

Output:Showing the AVL Tree before and after operations.

H/W & S/W Specifications:

Pentium –IV

Putty software

Linux Server with c compiler

Header filetypedef int ElementType;

/* START: fig4_35.txt */ #ifndef _AvlTree_H #define _AvlTree_H

struct AvlNode; typedef struct AvlNode *Position; typedef struct AvlNode *AvlTree;

AvlTree MakeEmpty( AvlTree T ); Position Find( ElementType X, AvlTree T ); Position FindMin( AvlTree T ); Position FindMax( AvlTree T ); AvlTree Insert( ElementType X, AvlTree T ); AvlTree Delete( ElementType X, AvlTree T ); ElementType Retrieve( Position P );

#endif /* _AvlTree_H *//* END */

Implementation:

#include <stdlib.h> #include "fatal.h"

64

Page 65: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

struct AvlNode { ElementType Element; AvlTree Left; AvlTree Right; int Height; };

AvlTree MakeEmpty( AvlTree T ) { if( T != NULL ) { MakeEmpty( T->Left ); MakeEmpty( T->Right ); free( T ); } return NULL; }

Position Find( ElementType X, AvlTree T ) { if( T == NULL ) return NULL; if( X < T->Element ) return Find( X, T->Left ); else if( X > T->Element ) return Find( X, T->Right ); else return T; }

Position FindMin( AvlTree T ) { if( T == NULL ) return NULL; else if( T->Left == NULL ) return T; else return FindMin( T->Left ); }

Position FindMax( AvlTree T ) { if( T != NULL ) while( T->Right != NULL ) T = T->Right;

65

Page 66: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

return T; }

/* START: fig4_36.txt */ static int Height( Position P ) { if( P == NULL ) return -1; else return P->Height; }/* END */

static int Max( int Lhs, int Rhs ) { return Lhs > Rhs ? Lhs : Rhs; }

/* START: fig4_39.txt */ /* This function can be called only if K2 has a left child */ /* Perform a rotate between a node (K2) and its left child */ /* Update heights, then return new root */

static Position SingleRotateWithLeft( Position K2 ) { Position K1;

K1 = K2->Left; K2->Left = K1->Right; K1->Right = K2;

K2->Height = Max( Height( K2->Left ), Height( K2->Right ) ) + 1; K1->Height = Max( Height( K1->Left ), K2->Height ) + 1;

return K1; /* New root */ }/* END */

/* This function can be called only if K1 has a right child */ /* Perform a rotate between a node (K1) and its right child */ /* Update heights, then return new root */

static Position SingleRotateWithRight( Position K1 ) { Position K2;

K2 = K1->Right; K1->Right = K2->Left; K2->Left = K1;

66

Page 67: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

K1->Height = Max( Height( K1->Left ), Height( K1->Right ) ) + 1; K2->Height = Max( Height( K2->Right ), K1->Height ) + 1;

return K2; /* New root */ }

/* START: fig4_41.txt */ /* This function can be called only if K3 has a left */ /* child and K3's left child has a right child */ /* Do the left-right double rotation */ /* Update heights, then return new root */

static Position DoubleRotateWithLeft( Position K3 ) { /* Rotate between K1 and K2 */ K3->Left = SingleRotateWithRight( K3->Left );

/* Rotate between K3 and K2 */ return SingleRotateWithLeft( K3 ); }/* END */

/* This function can be called only if K1 has a right */ /* child and K1's right child has a left child */ /* Do the right-left double rotation */ /* Update heights, then return new root */

static Position DoubleRotateWithRight( Position K1 ) { /* Rotate between K3 and K2 */ K1->Right = SingleRotateWithLeft( K1->Right );

/* Rotate between K1 and K2 */ return SingleRotateWithRight( K1 ); }

/* START: */ AvlTree Insert( ElementType X, AvlTree T ) { if( T == NULL ) { /* Create and return a one-node tree */ T = malloc( sizeof( struct AvlNode ) ); if( T == NULL ) FatalError( "Out of space!!!" ); else { T->Element = X; T->Height = 0;

67

Page 68: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

T->Left = T->Right = NULL; } } else if( X < T->Element ) { T->Left = Insert( X, T->Left ); if( Height( T->Left ) - Height( T->Right ) == 2 ) if( X < T->Left->Element ) T = SingleRotateWithLeft( T ); else T = DoubleRotateWithLeft( T ); } else if( X > T->Element ) { T->Right = Insert( X, T->Right ); if( Height( T->Right ) - Height( T->Left ) == 2 ) if( X > T->Right->Element ) T = SingleRotateWithRight( T ); else T = DoubleRotateWithRight( T ); } /* Else X is in the tree already; we'll do nothing */

T->Height = Max( Height( T->Left ), Height( T->Right ) ) + 1; return T; }/* END */

AvlTree Delete( ElementType X, AvlTree T ) { printf( "Sorry; Delete is unimplemented; %d remains\n", X ); return T; }

ElementType Retrieve( Position P ) { return P->Element; }

#include "avltree.h"#include <stdio.h>

main( ){ AvlTree T; Position P; int i; int j = 0;

T = MakeEmpty( NULL ); for( i = 0; i < 50; i++, j = ( j + 7 ) % 50 )

68

Page 69: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

T = Insert( j, T ); for( i = 0; i < 50; i++ ) if( ( P = Find( i, T ) ) == NULL || Retrieve( P ) != i ) printf( "Error at %d\n", i );

/* for( i = 0; i < 50; i += 2 ) T = Delete( i, T );

for( i = 1; i < 50; i += 2 ) if( ( P = Find( i, T ) ) == NULL || Retrieve( P ) != i ) printf( "Error at %d\n", i ); for( i = 0; i < 50; i += 2 ) if( ( P = Find( i, T ) ) != NULL ) printf( "Error at %d\n", i );*/ printf( "Min is %d, Max is %d\n", Retrieve( FindMin( T ) ), Retrieve( FindMax( T ) ) );

return 0;}

Result:

AVL Tree implemented with sample data.

Date: Signature of Instructor

Review Questions

1. Compute the time complexity for above algorithm?

EXERCISE NO: 14

CIRCULAR LINKED LIST

Learning Objectives:

To learn about:

To learn how to implement circular Linked List Technique.

69

Page 70: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

Problem Description:

In the last node of a list, the link field often contains a null reference, a special value used to indicate the lack of further nodes. A less common convention is to make it point to the first node of the list; in that case the list is said to be circular or circularly linked; otherwise it is said to be open or linear.

Input: Enter Data For constructing List.

Output: Showing Circular Linked List Data before and after performing operations.

H/W & S/W Specifications:Pentium –IV

Putty software

Linux Server with c compiler

Source Code:

#include<stdio.h>#include<stdlib.h>typedef struct Node { int data; struct Node *next;}node;void insert(node *pointer, int data){ node *start = pointer; /* Iterate through the list till we encounter the last node.*/ while(pointer->next!=start) { pointer = pointer -> next; } /* Allocate memory for the new node and put data in it.*/ pointer->next = (node *)malloc(sizeof(node)); pointer = pointer->next; pointer->data = data; pointer->next = start; }int find(node *pointer, int key){ node *start = pointer; pointer = pointer -> next; //First node is dummy node. /* Iterate through the entire linked list and search for the key. */ while(pointer!=start) { if(pointer->data == key) //key is found. { return 1; } pointer = pointer -> next;//Search in the next node. }

70

Page 71: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

/*Key is not found */ return 0;}void delete(node *pointer, int data){ node *start = pointer; /* Go to the node for which the node next to it has to be deleted */ while(pointer->next!=start && (pointer->next)->data != data) { pointer = pointer -> next; } if(pointer->next==start) { printf("Element %d is not present in the list\n",data); return; } /* Now pointer points to a node and the node next to it has to be removed */ node *temp; temp = pointer -> next; /*temp points to the node which has to be removed*/ pointer->next = temp->next; /*We removed the node which is next to the pointer (which is also temp) */ free(temp); /* Beacuse we deleted the node, we no longer require the memory used for it . free() will deallocate the memory. */ return;}void print(node *start,node *pointer){ if(pointer==start) { return; } printf("%d ",pointer->data); print(start,pointer->next);}

int main(){ /* start always points to the first node of the linked list. temp is used to point to the last node of the linked list.*/ node *start,*temp; start = (node *)malloc(sizeof(node)); temp = start; temp -> next = start; /* Here in this code, we take the first node as a dummy node. The first node does not contain data, but it used because to avoid handling special cases in insert and delete functions. */ printf("1. Insert\n");

71

Page 72: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

printf("2. Delete\n"); printf("3. Print\n"); printf("4. Find\n"); while(1) { int query; scanf("%d",&query); if(query==1) { int data; scanf("%d",&data); insert(start,data); } else if(query==2) { int data; scanf("%d",&data); delete(start,data); } else if(query==3) { printf("The list is "); print(start,start->next); printf("\n"); } else if(query==4) { int data; scanf("%d",&data); int status = find(start,data); if(status) { printf("Element Found\n"); } else { printf("Element Not Found\n"); } } }}

Result:

Circular Linked List technique was implemented & tested its performance with sample data.

Date: Signature of Instructor

Review Questions

72

Page 73: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

1. Compute the time complexity for above algorithm?

EXERCISE NO : 15

HEAP SORT

Learning Objectives:

To learn about:

To learn heap sort Technique.

73

Page 74: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

Problem Description:

A heap is a specialized tree-based data structure that satisfies the heap property: If A is a parent node of B then key(A) is ordered with respect to key(B) with the same ordering applying across the heap. Either the keys of parent nodes are always greater than or equal to those of the children and the highest key is in the root node (this kind of heap is called max heap) or the keys of parent nodes are less than or equal to those of the children and the lowest key is in the root node (min heap). Heaps are crucial in several efficient graph algorithms such as Dijkstra's algorithm, and in the sorting algorithm heapsort.

The operations commonly performed with a heap are:

create-heap: create an empty heap heapify: create a heap out of given array of elements find-max or find-min: find the maximum item of a max-heap or a minimum item of a

min-heap, respectively (aka, peek) delete-max or delete-min: removing the root node of a max- or min-heap, respectively increase-key or decrease-key: updating a key within a max- or min-heap, respectively insert: adding a new key to the heap merge: joining two heaps to form a valid new heap containing all the elements of

both.

Input: Enter Data For constructing Heap Tree. Later to call Heap sort.

Output: Display node value deleted from the list and finally we get sorted List.

H/W & S/W Specifications:Pentium –IV

Putty software

Linux Server with c compiler

Source Code:

void heapsort( input_type a[], unsigned int n ){int i; for( i=n/2; i>0; i-- ) /* build_heap */ perc_down (a, i, n ); for( i=n; i>=2; i-- ){ swap( &a[1], &a[i] ); /* delete_max */ perc_down( a, 1, i-1 );}}

74

Page 75: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

voidperc_down( input_type a[], unsigned int i, unsigned int n ){unsigned int child;input_type tmp; for( tmp=a[i]; i*2<=n; i=child ){ child = i*2; if( ( child != n ) && ( a[child+1] > a[child] ) ) child++; if( tmp < a[child] ) a[i] = a[child];else break;} a[i] = tmp;}

Result:

Heap sort technique was implemented & tested its performance with sample data.

Date: Signature of Instructor

Review Questions

1. Compute the time complexity for above algorithm?

EXERCISE NO : 16

AIRPORT SIMULATION

Learning Objectives:

To learn about:

To know how to apply queue for real time problems.

Problem Description:

75

Page 76: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

There is a small busy airport with only one runway. In each unit of time one plane can land or one plane can take off, but not both. Planes arrive ready to land or to take off at random times, so at any given unit of time, the runway may be idle or a plane may be landing or taking off. There may be several planes waiting either to land or to take off. Follow the steps given below to design the program.

1. Create two queues one for the planes landing and the other for planes taking off.2. Get the maximum number of units <endtime> for which the simulation program would run.3. Get the expected number of planes arriving in one unit <expectarrive> and number of planes ready to take off in one unit <expectdepart>.3. To display the statistical data concerning the simulation, declare following data members.

a. idletime - to store the number of units the runway was idleb. landwait - to store total waiting time required for planes landedc. nland - to store number of planes landedd. nplanes - to store number of planes processede. nrefuse - to store number of planes refused to land on airportf. ntakeoff - to store number of planes taken offg. takeoffwait - to store total waiting time taken for take off

Initialize the queue used for the plane landing and for the take offGet the data for <endtime>, <expectarrive> and <expectdepart> from the user.

The process of simulation would run for many units of time, hence run a loop in main( ) that would run from <curtime> to <endtime> where <curtime> would be 1 and <endtime> would be the maximum number of units the program has to be run.Generate a random number. Depending on the value of random number generated, perform following tasks.

1. If the random number is less than or equal to 1 then get data for the plane ready to land. Check whether or not the queue for landing of planes is full. If the queue is full then refuse the plane to land. If the queue is not empty then add the data to the queue maintained for planes landing.2. If the random number generated is zero, then generate a random number again. Check if this number is less than or equal to 1. If it is , then get data for the plane ready to take off. Check whether or not the queue for taking a plane off is full. If the queue is full then refuse the plane to take off otherwise add the data to the queue maintained for planes taking off.3. It is better to keep a plane waiting on the ground than in the air, hence allow a plane to take off only, if there are no planes waiting to land.4. After receiving a request from new plane to land or take off, check the queue of planes waiting to land, and only if the landing queue is empty, allow a plane to take off.5. If the queue for planes landing is not empty then remove the data of plane in the queue else run the procedure to land the plane. 6. Similarly, if the queue for planes taking off is not empty then remove the data of plane in the queue else run the procedure to take off the plane.7. If both the queues are empty then the runway would be idle.8. Finally, display the statistical data As given below.

Total number of planes processed Number of planes landed : Number of planes taken off : Number of planes refused use : Number of planes left ready to land : Number of planes left ready to take off :Percentage of time the runway was idle :Average wait time to land :

76

Page 77: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

Average wait time to take off :

Input: Enter Data required for this project.

Output: display the statistical data As given below.

Total number of planes processed Number of planes landed : Number of planes taken off : Number of planes refused use : Number of planes left ready to land : Number of planes left ready to take off : Percentage of time the runway was idle : Average wait time to land : Average wait time to take off :

H/W & S/W Specifications:Pentium –IV

Putty software

Linux Server with c compiler

Source Code:

/* Airport simulation */#include <stdio.h>#include <conio.h>#include <stdlib.h>#include <ctype.h>#include <math.h>#include <time.h>#include <limits.h>

#define MAX 3#define ARRIVE 0#define DEPART 1

struct plane{

int id ;int tm ;

} ;

struct queue{

int count ;int front ;int rear ;

struct plane p[MAX] ;} ;

77

Page 78: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

void initqueue ( struct queue * ) ;void addqueue ( struct queue *, struct plane ) ;struct plane delqueue ( struct queue * ) ;int size ( struct queue ) ;int empty ( struct queue ) ;int full ( struct queue ) ;

void initqueue ( struct queue *pq ){

pq -> count = 0 ;pq -> front = 0 ;pq -> rear = -1 ;

}

void addqueue ( struct queue *pq, struct plane item ){

if ( pq -> count >= MAX ){

printf ( "\nQueue is full.\n" ) ;return ;

}( pq -> count )++ ;

pq -> rear = ( pq -> rear + 1 ) % MAX ;pq -> p[pq -> rear] = item ;

}

struct plane delqueue ( struct queue *pq ){

struct plane p1 ;

if ( pq -> count <= 0 ){

printf ( "\nQueue is empty.\n" ) ;p1.id = 0 ;p1.tm = 0 ; }

else{

( pq -> count )-- ;p1 = pq -> p[pq -> front] ;pq -> front = ( pq -> front + 1 ) % MAX ;

}return p1 ;

}

int size ( struct queue q ){

return q.count ;}

int empty ( struct queue q ){

return ( q.count <= 0 ) ;

78

Page 79: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

}

int full ( struct queue q ){

return ( q.count >= MAX ) ;}

struct airport{

struct queue landing ;struct queue takeoff ;struct queue *pl ;struct queue *pt ;int idletime ;int landwait, takeoffwait ;int nland, nplanes, nrefuse, ntakeoff ;struct plane pln ;

} ;

void initairport ( struct airport * ) ;void start ( int *, double *, double * ) ;void newplane ( struct airport *, int, int ) ;void refuse ( struct airport *, int ) ;void land ( struct airport *, struct plane, int ) ;void fly ( struct airport *, struct plane, int ) ;void idle ( struct airport *, int ) ;void conclude ( struct airport *, int ) ;int randomnumber ( double ) ;void apaddqueue ( struct airport *, char ) ;struct plane apdelqueue ( struct airport *, char ) ;int apsize ( struct airport, char ) ;int apfull ( struct airport, char ) ;int apempty ( struct airport, char ) ;void myrandomize ( ) ;

void initairport ( struct airport *ap ){ initqueue ( &( ap-> landing ) ) ; initqueue ( &( ap -> takeoff ) ) ;

ap -> pl = &( ap -> landing ) ;ap -> pt = &( ap -> takeoff ) ;ap -> nplanes = ap -> nland = ap -> ntakeoff = ap -> nrefuse = 0 ;ap -> landwait = ap -> takeoffwait = ap -> idletime = 0 ;

}

void start ( int *endtime, double *expectarrive, double *expectdepart ){

int flag = 0 ;char wish ;

printf ( "\nProgram that simulates an airport with only one runway.\n" ) ;

79

Page 80: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

printf ( "One plane can land or depart in each unit of time.\n" ) ;printf ( "Up to %d planes can be waiting to land or take off at any time.\n", MAX ) ;printf ( "How many units of time will the simulation run?" ) ;scanf ( "%d", endtime ) ;myrandomize( ) ;do{

printf ( "\nExpected number of arrivals per unit time? " ) ;scanf ( "%lf", expectarrive ) ;printf ( "\nExpected number of departures per unit time? " ) ;scanf ( "%lf", expectdepart ) ;

if ( *expectarrive < 0.0 || *expectdepart < 0.0 ){

printf ( "These numbers must be nonnegative.\n" ) ;flag = 0 ;

}else{

if ( *expectarrive + *expectdepart > 1.0 ){

printf ( "The airport will become saturated. Read new numbers? " ) ; fflush ( stdin ) ;

scanf ( "%c", &wish ) ;if ( tolower ( wish ) == 'y' )

flag = 0 ;else

flag = 1 ;}else

flag = 1 ;}

} while ( flag == 0 ) ;}

void newplane ( struct airport *ap, int curtime, int action ){

( ap -> nplanes )++ ;ap -> pln.id = ap -> nplanes ;ap -> pln.tm = curtime ;

switch ( action ){

case ARRIVE :printf ( "\n" ) ;printf ( "Plane %d ready to land.\n", ap -> nplanes ) ;break ;

case DEPART :printf ( "\nPlane %d ready to take off.\n", ap -> nplanes ) ;break ;

}

80

Page 81: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

}

void refuse ( struct airport *ap, int action ){

switch ( action ){

case ARRIVE :

printf ( "\tplane %d directed to another airport.\n", ap -> pln.id ) ; break ;

case DEPART :

printf ( "\tplane %d told to try later.\n", ap -> pln.id ) ; break ;

}( ap -> nrefuse )++ ;

}

void land ( struct airport *ap, struct plane pl, int curtime ){

int wait ;

wait = curtime - pl.tm ;printf ( "%d: Plane %d landed ", curtime, pl.id ) ;printf ( "in queue %d units \n", wait ) ;( ap -> nland ) ++ ;( ap -> landwait ) += wait ;

}

void fly ( struct airport *ap, struct plane pl, int curtime ){

int wait ;

wait = curtime - pl.tm ;printf ( "%d: Plane %d took off ", curtime, pl.id ) ;printf ( "in queue %d units \n", wait ) ;( ap -> ntakeoff )++ ;( ap -> takeoffwait ) += wait ;

}

void idle ( struct airport *ap, int curtime ){

printf ( "%d: Runway is idle.\n", curtime ) ;ap -> idletime++ ;

}

void conclude ( struct airport *ap, int endtime ){

printf ( "\tSimulation has concluded after %d units.\n", endtime ) ;printf ( "\tTotal number of planes processed: %d\n", ap -> nplanes ) ;printf ( "\tNumber of planes landed: %d\n", ap -> nland ) ;printf ( "\tNumber of planes taken off: %d\n", ap -> ntakeoff ) ;printf ( "\tNumber of planes refused use: %d\n", ap -> nrefuse ) ;

81

Page 82: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

printf ( "\tNumber left ready to land: %d\n", apsize ( *ap, 'l' ) ) ;printf ( "\tNumber left ready to take off: %d\n", apsize ( *ap, 't' ) ) ;

if ( endtime > 0 )printf ( "\tPercentage of time runway idle: %lf \n", ( ( double ) ap ->

idletime / endtime ) * 100.0 ) ;

if ( ap -> nland > 0 )printf ( "\tAverage wait time to land: %lf \n", ( ( double ) ap -> landwait / ap -

> nland ) ) ;

if ( ap -> ntakeoff > 0 )printf ( "\tAverage wait time to take off: %lf \n", ( ( double ) ap ->

takeoffwait / ap -> ntakeoff ) ) ;}

int randomnumber ( double expectedvalue ){

int n = 0 ;double em ;double x ;

em = exp ( -expectedvalue ) ;x = rand( ) / ( double ) INT_MAX ;

while ( x > em ){

n++ ;x *= rand( ) / ( double ) INT_MAX ;

}

return n ;}

void apaddqueue ( struct airport *ap, char type ){

switch ( tolower( type ) ){

case 'l' : addqueue ( ap -> pl, ap -> pln ) ; break ;

case 't' : addqueue ( ap -> pt, ap -> pln ) ; break ;

}}

struct plane apdelqueue ( struct airport *ap, char type ){

struct plane p1 ;

switch ( tolower ( type ) ){

82

Page 83: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

case 'l' : p1 = delqueue ( ap -> pl ) ; break ;

case 't' : p1 = delqueue ( ap -> pl ) ; break ;

}

return p1 ;}

int apsize ( struct airport ap, char type ){

switch ( tolower ( type ) ){

case 'l' : return ( size ( *( ap.pl ) ) ) ;

case 't' : return ( size ( *( ap.pt ) ) ) ;

}

return 0 ;}

int apfull ( struct airport ap, char type ){

switch ( tolower ( type ) ){

case 'l' : return ( full ( *( ap.pl ) ) ) ;

case 't' : return ( full ( *( ap.pt ) ) ) ;

}

return 0 ;}

int apempty ( struct airport ap, char type ){

switch ( tolower ( type ) ){

case 'l' : return ( empty ( *( ap.pl ) ) ) ;

case 't' : return ( empty ( *( ap.pt ) ) ) ;

}

return 0 ;}

83

Page 84: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

void myrandomize( ){

srand ( ( unsigned int ) ( time ( NULL ) % 10000 ) ) ;}

void main( ){

struct airport a ;int i, pri, curtime, endtime ;double expectarrive, expectdepart ;struct plane temp ;

clrscr( ) ;

initairport ( &a );

start ( &endtime, &expectarrive, &expectdepart ) ;

for ( curtime = 1 ; curtime <= endtime ; curtime++ ){

pri = randomnumber ( expectarrive ) ;

for ( i = 1 ; i <= pri ; i++ ){

newplane ( &a, curtime, ARRIVE ) ;if ( apfull ( a, 'l' ) )

refuse ( &a, ARRIVE ) ;else

apaddqueue( &a, 'l' ) ;}

pri = randomnumber ( expectdepart ) ;for ( i = 1 ; i <= pri ; i++ ){

newplane ( &a, curtime, DEPART ) ;if ( apfull ( a, 't' ) ) refuse ( &a, DEPART ) ;else apaddqueue ( &a, 't' ) ;

}

if ( ! ( apempty ( a, 'l' ) ) ){

temp = apdelqueue ( &a, 'l' ) ;land ( &a, temp, curtime ) ;

}else{

if ( ! ( apempty ( a, 't' ) ) ){

temp = apdelqueue ( &a, 't' ) ;fly ( &a, temp, curtime ) ;

}else

84

Page 85: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

idle ( &a, curtime ) ;}

}

conclude ( &a, endtime ) ;

getch( ) ;}

Result:

Total number of planes processed Number of planes landed : Number of planes taken off : Number of planes refused use : Number of planes left ready to land : Number of planes left ready to take off : Percentage of time the runway was idle : Average wait time to land : Average wait time to take off :

Date: Signature of Instructor

EXERCISE NO : 17

CAR GARAGE SIMULATION

Learning Objectives:

To learn about:

To know how to apply de-queue.

Problem Description:

85

Page 86: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

Suppose Fundu Parking Garage contains 10 parking lanes, each with a capacity to hold 10 cars at a time. As each car arrives/departs, the values A/D (representing arrival /departure) is entered along with the car registration number. If a car is departing the data should get updated. If a new car is arriving then on the screen a message should be displayed indicating suitable parking slot for the car. Cars arrive at the south end of the garage and leave from the north end. If a customer arrives to pick up a car that is not the nothernmost, all cars to the north of the car are moved out, the car is driven out, and the other cars are restored in the same order that they were in originally. Whenever a car leaves, all cars to the south are moved forward so that at all times all the empty spaces are in the south part of the garage. Write a program that implements this parking system.

Input: Enter data about the car.Output: Display how those cars are arranged in garage will be displayed.

/* a car garage simulation using de-queue (link list implementation) */

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

#define TOP 1#define BOT 2

struct node{

char plate [15] ;struct node *link ;

} *front[5], *rear[5] ;

char plate[15], temp[15] ;int i ;

void add_dq ( struct node**, struct node**, int, char* ) ;char* del_dq ( struct node**, struct node**, int ) ;void push ( struct node**, char* ) ;char* pop ( struct node** ) ;void q_display ( struct node * ) ;

void main( ){

char ad ;int s, lane = -1, min, lc ;

clrscr( );while ( 1 ){

for ( i = 0 ; i < 5 ; i++ ){

printf( "lane %d: ", i ) ;q_display ( front[i] ) ;

}

86

Page 87: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

printf( "\nArrival/Departure/Quit? ( A/D/Q ): " ) ;ad = getch( ) ;

if ( toupper ( ad ) == 'Q' )exit ( 1 ) ;

printf ( "\nEnter license plate num:" ) ;gets ( plate ) ;ad = toupper ( ad ) ;

if ( ad == 'A' ) /* arrival of car */{

lane = -1 ; /* assume no lane is available */min = 10 ;for ( i = 0 ; i < 5 ; i++ ){

s = count ( front[i] ) ;if ( s < min ){

min = s ;lane = i ;

}}

if ( lane == -1 )printf ( "\nNo room available" ) ;

else{

add_dq ( &front[ lane ], &rear[ lane ], BOT, plate ) ;printf ( "\npark car at lane %d slot %d\n", lane, s ) ;

}}else{

if ( ad == 'D' ) /* departure of car */{

for ( i = 0 ; i < 5 ; ++i ){

s = search ( front[i], plate ) ;if ( s != -1 ){

lane = i ;break ;

}}

if ( i == 5 )printf ( "\nno such car!!\n" ) ;

else{

printf ( "\ncar found at lane %d slot %d\n", lane, s ) ;del_dq ( &front[ lane ], &rear[ lane ], s ) ;

}}else

87

Page 88: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

if ( ad == 'Q' )exit ( 1 ) ;

} }}

/* adds a new element at the end of queue */void add_dq ( struct node **f, struct node **r, int tb, char *p ){

struct node *q ;/* create new node */q = ( struct node * ) malloc ( sizeof ( struct node ) ) ;strcpy ( q -> plate, p ) ;q -> link = NULL ;

/* if the queue is empty */if ( *f == NULL )

*f = q ;else{

if ( tb == BOT )( *r ) -> link = q ;

else{

q -> link = *f ;*f = q ;return ;

}}*r = q ;

}

char* del_dq ( struct node **f, struct node **r, int n ){

struct node *q, *top = NULL ;/* if queue is empty */if ( *f == NULL )

printf ( "queue is empty" ) ;else{

if ( n == 0 ){

strcpy ( temp, ( *f ) -> plate ) ;q = *f ;*f = ( *f ) -> link ;free ( q ) ;return temp ;

}

/* locate node */for ( i = 0 ; i < n ; i++ ){

/* drive out cars */push ( &top, ( *f ) -> plate ) ;

88

Page 89: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

/* delete the node */q = *f ;*f = q -> link ;free ( q ) ;

}

/* delete the nth node */q = *f ;*f = q -> link ;free ( q ) ;

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

strcpy ( temp, pop ( &top ) ) ;

/* add the node */add_dq ( f, r, TOP, temp ) ;

}}

}

int count ( struct node *q ){

int c = 0 ;

/* traverse the entire linked list */while ( q!= NULL ){

q = q -> link ;c++ ;

}return c ;

}

int search ( struct node *q, char *p ){

int s = -1, c = 0 ;

while ( q != NULL ){

if ( strcmp ( p, q -> plate ) == 0 ){

s = c ;break ;

}else{

q = q -> link ;c++ ;

}}return ( s ) ;

}

89

Page 90: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

/* adds a new element to the top of stack */void push ( struct node **s, char* item ){

struct node *q ;q = ( struct node* ) malloc ( sizeof ( struct node ) ) ;strcpy ( q -> plate, item ) ;q -> link = *s ;*s = q ;

}/* removes an element from top of stack */char* pop ( struct node **s ){

struct node *q ;

/* if stack is empty */if ( *s == NULL ){

return NULL ;}else{

q = *s ;strcpy ( temp, q -> plate ) ;*s = q -> link ;free ( q ) ;return ( temp ) ;

}}void q_display ( struct node *q ){

while( q != NULL ){

printf ( "%s", q -> plate ) ;q = q -> link ;

}printf ( "\n" ) ;

}

Result:

Shows how cargarage is maintained

Date: Signature of Instructor

90

Page 91: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

EXERCISE NO : 18

SIMULATE A DICTIONARY

Learning Objectives:

To learn about:

To know how to apply Linked list and Linear search .

Problem Description:

Write a program to simulate a dictionary using linked list. It should be a menu driven program with the options for adding a word and its meanings, searching a word and displaying the dictionary. Steps to develop the program are as given below:

91

Page 92: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

1. Declare a structure with the fields as - a word, - meaning of a word- counter that holds the number of meanings- link to the next node.

Each word added to the list can have maximum 5 meaning(s). Hence, variable used to store meaning(s) of a word would be a two dimensional character array.

2. The program should have following menu.

- Add a word- Search for a word- Show dictionary- Exit

Input: Enter a word and their meaning to register a word in the dictionary.Output: Display the meaning of the word by entering a word.

/* Dictionary with Linear search implementation*/

#include <stdio.h>#include <conio.h>#include <malloc.h>#include <stdlib.h>#include <string.h>#include <ctype.h>

struct node{

char data [ 20 ] ;char m [ 5 ] [ 20 ] ;int mcount ;struct node * link ; } ;

struct node * dic [ 26 ] ;

void add ( char * ) ;int search ( char * ) ;void show( ) ;void deldic( ) ;

void main( ){

char word [ 20 ] , ch ;int i ;

clrscr( ) ;

while ( 1 ){

clrscr( ) ;printf ( "\n\t\tDictionary\n" ) ;printf ( "\n\t\t1.Add Word.\n" ) ;printf ( "\t\t2.Search Word.\n" ) ;

92

Page 93: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

printf ( "\t\t3.Show Dictionary.\n" ) ;printf ( "\t\t0.Exit." ) ;printf ( "\n\n\t\tYour Choice ") ;scanf ( "%d", &ch ) ;

switch ( ch ){

case 1 :

printf ( "\nEnter any word : " ) ;fflush ( stdin ) ;gets ( word ) ;add ( word ) ;

break ;

case 2 :

printf ( "\nEnter the word to search : " ) ;fflush ( stdin ) ;gets ( word ) ;i = search ( word ) ;if ( ! i )

printf ( "Word does not exists." ) ;getch( ) ;

break ;

case 3 :

show( ) ;getch( ) ;

break ;case 0 :

deldic( ) ;exit ( 0 ) ;

default :

printf ( "\nWrong Choice" ) ;}

}}

void add ( char * str ){

int i, j = toupper ( str [ 0 ] ) - 65 ;struct node * r, * temp = dic [ j ], * q ;char mean [ 5 ] [ 20 ], ch = 'y' ;

i = search ( str ) ;if ( i )

93

Page 94: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

{printf ( "\nWord already exists." ) ;getch( ) ;return ;

}q = ( struct node * ) malloc ( sizeof ( struct node ) ) ;strcpy ( q -> data, str ) ;q -> link = NULL ;

for ( i = 0 ; tolower ( ch ) == 'y' && i < 5 ; i++ ){

fflush ( stdin ) ;printf ( "\n\nEnter the meaning(s) : " ) ;gets ( mean [ i ] ) ;strcpy ( q -> m [ i ] , mean [ i ] ) ;if ( i != 4 )

printf ( "\nAdd more meanings (y/n) " ) ;else

printf ( "You cannot enter more than 5 meanings." ) ;fflush ( stdin ) ;ch = getche( ) ;

}

q -> mcount = i ;if ( dic [ j ] == NULL || strcmp ( dic [ j ] -> data, str ) > 0 ){

r = dic [ j ] ;dic [ j ] = q ;q -> link = r ;return ;

}

else{

while ( temp != NULL ){

if ( ( strcmp ( temp -> data, str ) < 0 ) && ( ( strcmp ( temp -> link -> data, str ) > 0 ) ||

temp -> link == NULL ) ){

q -> link = temp -> link ;temp -> link = q ;return ;

}temp = temp -> link ;

}}

}

int search ( char *str ){

struct node *n ;char temp1 [ 20 ] ;

94

Page 95: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

char temp2 [ 20 ] ;int i ;

n = dic [ toupper ( str [ 0 ] ) - 65 ] ;strcpy ( temp2, str ) ;strupr ( temp2 ) ;

while ( n != NULL ){

strcpy ( temp1, n -> data ) ;

if ( strcmp ( strupr ( temp1 ), temp2 ) == 0 ){

printf ( "\n%s\t\t%s", n -> data, n -> m [ 0 ] ) ;for ( i = 1 ; i < n -> mcount ; i++ )

printf ( "\n\t\t%s", n -> m [ i ] ) ;return 1 ;

}n = n -> link ;

}return 0 ;

}

void show( ){

struct node *n ;int i, j ;

printf ( "Word\t\tMeaning\n" ) ;for ( i = 0 ; i <= 30 ; i++ )

printf ( "-" ) ;

for ( i = 0 ; i <= 25 ; i++ ){

n = dic [ i ] ;while ( n != NULL ){

printf ( "\n%s\t\t%s", n -> data, n -> m [ 0 ] ) ;for ( j = 1 ; j < n -> mcount ; j++ )

printf ( "\n\t\t%s", n -> m [ j ] ) ;n = n -> link ;

}}

}

void deldic( ){

struct node *n, *t ;int i ;

for ( i = 0 ; i <= 25 ; i++ ){

n = dic [ i ] ;

95

Page 96: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

while ( n != NULL ){

t = n -> link ;free ( n ) ;n = t ;

}}

}

Result:

Shows meaning of the word that was added by end user in their dictionary.

Date: Signature of Instructor

EXERCISE NO : 19

DUPLICATE FILE FINDER

Learning Objectives:

To learn about:

To know how to apply Binary search .

Problem Description:

When the hard disk is new the files and directories are properly organized. As the hard disk

grows old, some laxity sets in and one tends to create files with duplicate names in different

directories. Write a program to locate these duplicate filenames.

Input: Takes data from the system directory.

96

Page 97: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

Output: Display the duplicate files with their path.

/* Program to find files with duplicate names using binary search tree */

#include <stdio.h>#include <conio.h>#include <dos.h>#include <dir.h>#include <string.h>#include <alloc.h>

struct btreenode{

struct btreenode *leftchild ;char data[13] ; /* file name */char *loc ; /* location of filename */struct btreenode *rightchild ;

} *bt = NULL ;

void disktree( ) ;int insert ( struct btreenode **, char*, char* ) ;

void main( ){

char current_dir[32] ;

clrscr( ) ;

getcwd ( current_dir, 32 ) ;chdir ( "\\" ) ;disktree( ) ;chdir ( current_dir ) ;

getch( ) ;}

void disktree( ){

struct ffblk file ;int flag ;char loc[80] ;

getcwd ( loc, 80 ) ;flag = findfirst ( "*.*", &file, FA_NORMAL | FA_RDONLY | FA_HIDDEN |

FA_SYSTEM | FA_LABEL | FA_DIREC | FA_ARCH ) ;

while ( flag == 0 ){

if ( file.ff_name[0] != '.' ){

if ( file.ff_attrib == FA_DIREC && file.ff_fsize == 0 ){

97

Page 98: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

chdir ( file.ff_name ) ;disktree( ) ;chdir ( loc ) ;

}else

insert ( &bt, loc, file.ff_name ) ;}flag = findnext ( &file ) ;

}}

/* inserts a new node in a binary search tree */int insert ( struct btreenode **sr, char* l, char* f ){

char *p ;int flag ;

if ( *sr == NULL ){

*sr = ( struct btreenode * ) malloc ( sizeof ( struct btreenode ) ) ;

if ( *sr == NULL ){

printf ( "\nOut of memory." ) ;exit ( 1 ) ;

}

( *sr ) -> leftchild = NULL ;( *sr ) -> rightchild = NULL ;strcpy ( ( *sr ) -> data, f ) ;p = ( char * ) malloc ( ( strlen ( l ) + 1 ) ) ;

if ( p == NULL ){

printf ( "\nOut of memory." ) ;exit ( 1 ) ;

}

strcpy ( p, l ) ;( *sr ) -> loc = p ;

}else{

flag = strcmp ( ( *sr ) -> data, f ) ;

if ( flag == 0 ){

printf ( "org: %s", ( *sr ) -> loc ) ;

if ( strlen ( ( *sr ) -> loc ) > 4 )printf ( "\\" ) ;

printf ( "%s\n", ( *sr ) -> data ) ;printf ("dup: %s", l ) ;

98

Page 99: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

if ( strlen ( l ) > 4 )printf ( "\\" ) ;

printf ( "%s\n\n", f ) ;}else if ( flag < 0 )

insert ( &( ( *sr ) -> leftchild ), l, f ) ;else

insert ( &( ( *sr ) -> rightchild ), l, f ) ;}return ;

}

Result:

Shows List of files on console that was having duplicate files.

Date: Signature of Instructor

EXERCISE NO : 20

SORTING OF A RECORDS

Learning Objectives:

To learn about:

To know how to apply Binary search .

Problem Description:

Write a program that asks user an ID, name, age and salary of 5 employees. Store all the ID's

into one array and sort the array in asscending order. Now to display the records in asscending

order search for each elements from the array into records and display the corresponding

records.

Input: Enter record details user id , age, and salry of 5 employees.

99

Page 100: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

Output: Display the records in asscending order search for each elements from the array

into records and display the corresponding records

/* Sorting of a structure on names using bubble sort */

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

void main( ){

struct emp{

char empid[7] ;char name[25] ;int age ;float sal ;

} ;

int i, j ;struct emp e[5] ;char id[5][7], temp[7] ;float ff ( float ) ;

clrscr( ) ;printf ( "Enter empid, name, age and salary :-\n") ;for ( i = 0 ; i <= 4 ; i++ ){

scanf ( "%s %s %d %f", e[i].empid, e[i].name, &e[i].age, &e[i].sal ) ;strcpy ( id[i], e[i].empid ) ;

}

for ( i = 0 ; i <= 3 ; i++ ){

for ( j = 0 ; j <= 3 - i ; j++ ){

if ( strcmp ( id[j], id[j + 1] ) > 0 ){

strcpy ( temp, id[j] ) ;strcpy ( id[j], id[j + 1] ) ;strcpy ( id[j + 1], temp ) ;

}}

}

printf ( "\nRecords after sorting") ;printf ( "\nName, age and salary after sorting :-\n") ;for ( i = 0 ; i <= 4 ; i++ ){

for ( j = 0 ; j <= 4 ; j++ ){

if ( strcmp( id[i], e[j].empid ) == 0 )

100

Page 101: section2becm.weebly.com€¦ · Web viewFor s = {1,-5, 2,-1, 3}, we know that {1}, {2,-1, 3}, and {-5, 2} are all contiguous subsequences of s—whereas h1,2,3i is not. Among such

printf ( "%s %s %d %f\n", e[j].empid, e[j].name, e[j].age, e[j].sal ) ;

}}

getch( ) ;}

float ff ( float f ){

float *f1 = &f ; return *f1 ;}

Result:

Shows Sorted records in ascending order

Date: Signature of Instructor

101