0% found this document useful (0 votes)
77 views74 pages

DS LAB Updated

Uploaded by

Arya Sathyan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views74 pages

DS LAB Updated

Uploaded by

Arya Sathyan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 74

Program 1.

Given {4,7,3,2,1,7,9,0} find the location of 7 using Binary search and also display its first
occurrence.

FLOW CHART
ALGORITHAM
BINARY_SEARCH(A, lower_bound, upper_bound, VAL)

Step 1: [INITIALIZE] SET BEG = lower_bound

END = upper_bound, POS = - 1

Step 2: Repeat Steps 3 and 4 while BEG <=END

Step 3: SET MID = (BEG + END)/2

Step 4: IF A[MID] = VAL


SET POS = MID
PRINT POS
Go to Step 6
ELSE IF A[MID] > VAL
SET END = MID - 1
ELSE
SET BEG = MID + 1
[END OF IF]
[END OF LOOP]

Step 5: IF POS = -1
PRINT "VALUE IS NOT PRESENT IN THE ARRAY"
[END OF IF]

Step 6: EXIT

SOURCE CODE

#include<stdio.h>
#include<conio.h>
void main()
{
int a[10]={4,7,3,2,1,7,9,0};
int i, j, n, low, high, mid, item, temp, key;
clrscr();
n=8;
printf("\n Given Array elements are:\n");
for(i=0;i<n;i++)
printf("\n%d",a[i]);
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf("\n Sorted Array elements are");
for(i=0;i<n;i++)
printf("\n %d",a[i]);
printf("\n enter the element to be searched");
scanf("%d",&key);
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(key==a[mid])
{
printf("\n key %d found succesfully at position %d",key,mid++);
break;
}
else if(key<a[mid]) high=mid-1;
else low=mid+1;
}
if(low>high)
printf("\n key %d not found",key);
getch();
}
OUTPUT :
Program 2 : Given{5,3,1,6,0,2,4} order the numbers in ascending order using Quick sort.
FLOW CHART :

ALGORITHAM
PARTITION (ARR, BEG, END, LOC)
Step 1: [INITIALIZE] SET LEFT = BEG, RIGHT = END, LOC = BEG, FLAG =

Step 2: Repeat Steps 3 to 6 while FLAG =

Step 3: Repeat while ARR[LOC] <=ARR[RIGHT]


AND LOC != RIGHT
SET RIGHT = RIGHT – 1
[END OF LOOP]
Step 4: IF LOC = RIGHT
SET FLAG = 1
ELSE IF ARR[LOC] > ARR[RIGHT]
SWAP ARR[LOC] with ARR[RIGHT]
SET LOC = RIGHT

[END OF IF]

Step 5: IF FLAG = 0
Repeat while ARR[LOC] >= ARR[LEFT] AND LOC != LEFT
SET LEFT = LEFT + 1

[END OF LOOP]

Step 6:IF LOC = LEFT


SET FLAG = 1
ELSE IF ARR[LOC] < ARR[LEFT]
SWAP ARR[LOC] with ARR[LEFT]
SET LOC = LEFT
[END OF IF]
[END OF IF]

Step 7: [END OF LOOP]

Step8: END

QUICK_SORT (ARR, BEG, END)

Step1: IF (BEG < END)


CALL PARTITION (ARR, BEG, END, LOC)
CALL QUICKSORT(ARR, BEG, LOC - 1)
CALL QUICKSORT(ARR, LOC + 1, END)
[END OF IF]

Step2: END

SOURCE CODE

#include <stdio.h>
#include<conio.h>
void quicksort (int [], int, int);
void main()
{
int list[50];
int size, i;
clrscr();
printf("Enter the number of elements: ");
scanf("%d", &size);
printf("Enter the elements to be sorted:\n");
for (i = 0; i < size; i++)
{
scanf("%d", &list[i]);
}
quicksort(list, 0, size - 1);
printf("After applying quick sort\n");
for (i = 0; i < size; i++)
{
printf("%d ", list[i]);
}
printf("\n");

getch();
}
void quicksort(int list[], int low, int high)
{
int pivot, i, j, temp; if (low < high)
{
pivot = low; i = low;
j = high; while (i < j)
{
while (list[i] <= list[pivot] && i <= high)
{
i++;
}
while (list[j] > list[pivot] && j >= low)
{
j--;
}
if (i < j)
{
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
temp = list[j];
list[j] = list[pivot];
list[pivot] = temp;
quicksort(list, low, j - 1);
quicksort(list, j + 1, high);
}
}

OUTPUT
Program 3: Perform the Merge Sort on the input {75,8,1,16,48,3,7,0} and display the output in descending order.

FLOW CHART
ALGORITHM
Step1: [INITIALIZE] SET I = BEG, J = MID + 1, INDEX = 0

Step 2: Repeat while (I <= MID) AND (J<=END)


IF ARR[I] < ARR[J]
SET TEMP[INDEX] = ARR[I]
SET I = I + 1
ELSE
SET TEMP[INDEX] = ARR[J]
SET J = J + 1 [END OF IF]
SET INDEX = INDEX + 1
[END OF LOOP]
Step 3: [Copy the remaining elements of right sub-array, if any]
IF I > MID
Repeat while J <= END
SET TEMP[INDEX] = ARR[J]
SET INDEX = INDEX + 1, SET J = J + 1
[END OF LOOP]
[Copy the remaining elements of
left sub-array, if any]
ELSE
Repeat while I <= MID
SET TEMP[INDEX] = ARR[I]
SET INDEX = INDEX + 1, SET I = I + 1
[END OF LOOP]
[END OF IF]

Step 4: [Copy the contents of TEMP back to ARR] SET K = 0

Step 5: Repeat while K < INDEX


SET ARR[K] = TEMP[K]
SET K = K + 1
[END OF LOOP]

Step 6: Exit

MERGE_SORT(ARR, BEG, END)

Step 1: IF BEG < END


SET MID = (BEG + END)/2
CALL MERGE_SORT (ARR, BEG, MID)
CALL MERGE_SORT (ARR, MID + 1, END)
MERGE (ARR, BEG, MID, END)
[END OF IF]
Step 2: END
SOURCE CODE

#include<stdio.h>
#include<conio.h>
voidmergesort(int a[],inti,int j);
void merge(int a[],int i1,int j1,int i2,int j2);
void main()
{
int a[8]={75,8,1,16,48,3,7,0},i;
clrscr();
printf("Array elements are:");
for(i=0;i<8;i++)
printf("%d\t",a[i]);
mergesort(a,0,8-1);
printf("\nSorted array is :");
for(i=0;i<8;i++)
printf("%d\t",a[i]);
getch();
}
void mergesort(int a[],int i, int j)
{
int mid;
if(i<j)
{
mid=(i+j)/2;
mergesort(a, i, mid);
mergesort(a,mid+1,j);
merge(a,i,mid,mid+1,j);
//merging of two sorted sub-arrays
}
}
void merge(int a[],int i1,int j1,int i2,int j2)
{
int temp[50];
int i, j, k;
i=i1;
j=i2;
k=0;
while(i<=j1 && j<=j2)
{
if(a[i]>a[j]) temp[k++]=a[i++];
else temp[k++]=a[j++];
}
while(i<=j1) temp[k++]=a[i++];
while(j<=j2) temp[k++]=a[j++];
for(i=i1,j=0;i<=j2;i++,j++)
a[i]=temp[j];
}

OUTPUT
Program 4: Write a program to insert the elements 61,16,8,27 into singly linked list and delete 8,61,27 from the list.
Display your list after each insertion and deletion.

FLOW CHART

//For creating a node


//For deleting the node:

ALGORITHAM:

//Insert at the beginning of the link


Step1: AVAIL=NULL,then WRITE: overflow and exit
Step2: set NEW:=AVAIL and AVAIL:=LINK[AVAIL]
Step3:set INFO[NEW]:=ITEM
Step4:set LINK[NEW]:=START
Step5:set START:=NEW
Step6: Exit
//Insert after given node
Step1: IF PTR=NULL WRITE:overflow
[go to step10]
[end of IF]
Step2: set NEW_NODE=PTR
Step3: set PTR=PTR->NEXT
Step4:set NEW_NODE->DATA=VAL
Step5:set NEW_NODE=NEXT=NULL
Step6:set PTR=HEAD
Step7:Repeat Step 8 While PTR->NEXT!=NULL
Step8;set PTR->NEXT[END OF LOOP]
Step9;set PTR->NEXT=NEW_NODE
Step10:EXIT

//Insertion at the end of the link

Step1:IF PTR=NULL WRITE: overflow


GOTO STEP 10[END IF]
Step2:set NEW_NODE=PTR
Step3:set PTR=PTR->NEXT
Step4:set NEW_NODE->DATA=VAL
Step5:set NEW_NODE->NEXT=NULL
Step6:set PTR=HEAD
Step7:Repeat Step 8 While PTR->NEXT!=NULL
Step8:Set PTR=PTR->NEXT
[END LOOP]
Step9:Set PTR->NEXT=NEW_NODE
Step10:EXIT

//Deletion from beginning:

Step1:IF HEAD=NULL WRITE:underflow


GOTO Step5
[END IF]
Step2:Set PTR=HEAD
Step3:Set HEAD=HEAD->NEXT
Step4:FREE PTR
Step5:EXIT

//Deletion from in between:

Step1:IF HEAD=NULL WRITE:underflow


GOTO STEP10
[END IF]
Step2:TEMP=HEAD
Step3:Set I=0
Step4:Repeat Step 5 to 8 until
I<LOC<li=” “</LOC<>
Step5:TEMP1=TEMP
Step6:TEMP=TEMP->NEXT
Step7:IF TEMP=NULL
WRITE:”desired node not present”
END OF IF
Step8:I=I+1
END IF
Step9:TEMP->NEXT=TEMP->NEXT
Step10:FREE TEMP
Step11:EXIT

//Deletion from the end:

Step1:IF HEAD=NULL
Step2:set PTR=HEAD
Step3:Repeat Step 4 and 5
While PTR->NEXT!=NULL
Step4:set PRE PTR=PTR
Step5:set PTR=PTR->NEXT
Step6:set PRE PTR->NEXT=NULL
Step7:FREE PTR
Step8:EXIT

SOURCE CODE

#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>

struct node
{
int value;
struct node *next;
};

void insert();
void display();
void delete();
int count();

typedef struct node DATA_NODE;

DATA_NODE *head_node, *first_node, *temp_node = 0, *prev_node, next_node;


int data;
int main()
{
int option = 0;
clrscr();
printf("Singly Linked List Example - All Operations\n");
while (option < 4)
{
printf("\nOptions\n");
printf("1 : Insert into Linked List \n");
printf("2 : Delete from Linked List \n");
printf("3 : Display Linked List\n");
printf("Others : Exit()\n");
printf("Enter your option:");

scanf("%d", &option);

switch (option)
{
case 1:
insert();
display();
break;
case 2:
delete();
display();
break;
case 3:
display();
break;

default:
break;
}
}

return 0;
}

void insert()
{
printf("\n Enter Element for Insert Linked List : \n");
scanf("%d", &data);

temp_node = (DATA_NODE *) malloc(sizeof (DATA_NODE));


temp_nod >value = data;
if (first_node == 0)
{
first_node = temp_node;
}
else
{
head_node->next = temp_node;
}
temp_node->next = 0;
head_node = temp_node;
fflush(stdin);
}

void delete()
{
int countvalue, pos, i = 0;
countvalue = count();
temp_node = first_node;

printf("\nEnter Position for Delete Element : \n");


scanf("%d", &pos);

if (pos> 0 &&pos<= countvalue)


{
if (pos == 1)
{
temp_node = temp_node -> next;
first_node = temp_node;
printf("\nDeleted Successfully \n\n");
}
else {
while (temp_node != 0)
{
if (i == (pos - 1))
{
prev_node->next =temp_node->next;
if(i ==(countvalue - 1))

{
head_node = prev_node;
}
printf("\nDeleted Successfully \n\n");
break;
}
else
{
i++;
prev_node = temp_node;
temp_node = temp_node -> next;
}
}
}
} else
printf("\nInvalid Position \n\n");
}

void display()
{
int count = 0;
temp_node = first_node;
printf("\nDisplay Linked List : \n");
while (temp_node != 0)
{

printf("# %d # ", temp_node->value);


count++;
temp_node = temp_node -> next;
}
printf("\nNo Of Items In Linked List : %d\n", count);
}

int count()
{
int count = 0;
temp_node = first_node;
while (temp_node != 0)
{
count++;
temp_node = temp_node -> next;
}
printf("\nNo Of Items In Linked List : %d\n", count);
return count;
}

OUTPUT
Program 5: Write a program to add 6x3 +10x2+0x+5 and 4x2 +2x+1 using linked list.

FLOW CHART
ALGORTHIM

ALGORITHM:
Step1:Loop around all values of linked list and follow step 2and 3
Step2:IF the value of nodes exponent is greater copy this node to result node and head ->NEXT NODE
Step3:IF value of both nodes exponent is same add the coefficient and then copy the added value with
node to result.
Step4:Print the resultant node
Step5:End

SOURCE CODE

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

struct Node
{
intcoeff;
intpow;
struct Node* next;
};

void readPolynomial(struct Node** poly)


{
int coeff, exp, cont;
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
*poly = temp;
do
{
printf("\n Coeffecient: ");
scanf("%d", &coeff);
printf("\n Exponent: ");
scanf("%d", &exp);
temp->coeff = coeff;
temp->pow = exp;
temp-> next = NULL;
printf("\nHave more terms? 1 for y and 0 for no: ");
scanf("%d", &cont);
if(cont)
{
temp->next = (struct Node*)malloc(sizeof(struct Node));
temp = temp->next;
temp->next = NULL;
}
}while(cont);
}

void displayPolynomial(struct Node* poly)


{
printf(" Polynomial expression is: ");
while(poly != NULL)
{
printf("%dX^%d", poly->coeff, poly->pow);
poly = poly->next;
if(poly != NULL)
printf("+");
}
}

void addPolynomials(struct Node** result, struct Node* first, struct Node* second)
{
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->next = NULL;
*result = temp; while(first && second)
{
if(first->pow> second->pow)
{
temp->coeff = first->coeff;
temp->pow = first->pow;
first = first->next;
}

else if(first->pow< second->pow)


{

}
else }
{
t f = second->coeff; temp-
e >pow = second->pow;
m second = second->next;
p
-
>
c temp->coeff = first->coeff + second->coeff;
o temp->pow = first->pow;
e first = first->next;
f second = second->next;

if(first && second)


{
temp->next = (struct Node*)malloc(sizeof(struct Node));
temp = temp->next;
temp->next = NULL;
}

}
while(first || second)
{
temp->next = (struct Node*)malloc(sizeof(struct Node));
temp = temp->next;
temp->next = NULL;

if(first)
{
temp->coeff = first->coeff;
temp->pow = first->pow;
first = first->next;
}

else if(second)
{
temp->coeff = second->coeff;
temp->pow = second->pow;
second = second->next;
}
}
}

void main()
{

struct Node* first = NULL;


struct Node* second = NULL;
struct Node* result = NULL;
clrscr();
printf("\nEnter the corresponding data:-\n");
printf("\nFirst polynomial:\n");
readPolynomial(&first);
printf("\nFirst");

displayPolynomial(first);
printf("\nSecond polynomial:\n");
readPolynomial(&second);
printf("\nSecond");
displayPolynomial(second);
addPolynomials(&result, first, second);
printf("\n\nAdded");
displayPolynomial(result);
getch();

}
OUTPUT
DATA STRUCTURE LAB

27
DATA STRUCTURE LAB

Program 6: Write a program to push 5,9,34,17,32 into stack and pop 3 times from
the stack, also display the popped numbers.

FLOW CHART

28
DATA STRUCTURE LAB

29
DATA STRUCTURE LAB

DISPLAY

30
DATA STRUCTURE LAB

ALGORITHM

PUSH()

Step1:begin
Step2: if top = n then stack full
Step3: top = top + 1
Step4:stack (top) : = item; Step5:end

POP()

Step1:begin
Step2: IF top = 0 then stack empty;
Step3: item := stack(top);
Step4:top = top - 1; Step5:end;

PEEK (STACK, TOP)

Step1: if top = -1 then stack empty


31
DATA STRUCTURE LAB

Step2:item = stack[top]
Step3: return item
Step4:End

SOURCE CODE

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
Structstack
{
int data;
Structstack*next;
};
Typedef Structstack S;
S*top;
void push();
void pop();
void display();
void main()
{
int ch;
top=(S*)malloc(sizeof(S));
top=NULL;
while(1)
{
clrscr();
printf("1.PUSH\n2.POP\n3.DISPLAY\n4.EXIT\n");
printf("\nEnteryourchoice:");
scanf("%d",&ch);
switch(ch)
{
case 1:push();
break;
case 2:pop();
break;
case 3:display();
break;
case4:exit(0);
break;
default:printf("InvalidChoice\n");
}
getch();
32
DATA STRUCTURE LAB

}
void push()
{
S*temp;
temp=(S*)malloc(sizeof(S));
printf("Enter the element:");
scanf("%d",&temp->data);
if(top==NULL)
{
temp->next=NULL;
top=temp;
}
else
{
temp->next=top;
top=temp;
}
printf("The %d element PUSHED succefully into the Stack\n",temp->data);
}
void pop()
{
S*temp;
temp=top;
if(top==NULL)
printf("StackUnderflow\n");
else
{
top=top->next;
printf("Element deleted is%d",temp->data); free(temp);
}
}
void display()
{
S*temp;
temp=top;
if(top==NULL)
printf("Stack is Empty\n"); else
{

printf("Elements in Stack are:");


while(temp!=NULL)
{
printf("%d",temp->data);
temp=temp->next;
33
DATA STRUCTURE LAB

}
}
}

OUTPUT

34
DATA STRUCTURE LAB

Program 7 : Write a recursive program to find GCD of 4,6,8.

FLOW CHART

ALGORITHM:

Step1:GCD(x,y)
Step2:begin IF(y=0) return x
else
Cal GCD(y, x%y)
[END IF]
Step3:End

35
DATA STRUCTURE LAB

SOURCE CODE

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

intfind_gcd(int , int);
void main()
{
int a, b, c, gcd1,gcd2;
clrscr();
printf("\n\nEnter three numbers to find GCD of \n");
scanf("%d%d%d", &a, &b, &c);
if(a==0 && b==0 && c==0)
{
printf("\nInvalid number");
exit(0);
}
gcd1=gcd(a,b);
gcd2=gcd(c,gcd1);
printf("\n\nGCD of %d ,%d and %d is: %d\n\n", a, b, c,gcd2);
getch();
}

// defining the function intgcd(int x, int y)


{
if(x > y) gcd(x-y, y);
else if(y > x) gcd(x, y-x);
else
return x;
}

OUTPUT

36
DATA STRUCTURE LAB

37
DATA STRUCTURE LAB

Program 8 : Write a program to insert the elements {5,7,0,6,3,9} into circular queue and delete 6,9 &
5 from it(using linked list implementation).

FLOW CHART

38
DATA STRUCTURE LAB

ALGORITHM

Algorithm to insert an element in a circular queue

39
DATA STRUCTURE LAB

Step 1: IF (REAR+1)%MAX = FRONT


Write " OVERFLOW "
Go to step 4
[End OF IF]

Step 2: IF FRONT = -1 and REAR = -1


SET FRONT = REAR = 0
ELSE IF REAR = MAX - 1 and FRONT ! = 0
SET REAR = 0
ELSE
SET REAR = (REAR + 1) % MAX
[END OF IF]

Step 3: SET QUEUE[REAR] = VAL

Step 4: EXIT

Algorithm to delete an element from the circular queue

Step 1: IF FRONT = -1
Write " UNDERFLOW "
Go to Step 4
[END of IF]

Step 2: SET VAL = QUEUE[FRONT]

Step 3: IF FRONT = REAR


SET FRONT = REAR = -1
ELSE
IF FRONT = MAX -1
SET FRONT = 0
ELSE
SET FRONT = FRONT + 1
[END of IF]
[END OF IF]

Step 4: EXIT

40
DATA STRUCTURE LAB

SOURCE CODE

#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* next;
};
struct node *f = NULL;
struct node *r = NULL;
void enqueue(int d) //Insert elements in Queue
{
struct node* n;
n = (struct node*)malloc(sizeof(struct node));
n->data = d;
n->next = NULL;
if((r==NULL)&&(f==NULL))
{
f = r = n;
r->next = f;
}
else
{
r->next = n; r = n;
n->next = f;

}
}
Void dequeue()
{
struct node* t;
t = f;
if((f==NULL)&&(r==NUL
L))
printf("\nQueue is Empty");
else if(f == r)
{

f = r = NULL;
free(t);

41
DATA STRUCTURE LAB

else{
f = f->next;
r->next = f;
free(t);
}

}
void print()
{
// Print the elements of Queue
struct node* t;
t = f;
if((f==NULL)&&(r==NULL))
printf("\nQueue is Empty");
else
{
do{

printf("\n%d",t->data);
t = t->next;
}while(t != f);
}
}
int main()
{
int opt,n,i,data;
printf("Enter Your Choice:-");
do{
printf("\n\n1 for Insert the Data in Queue\n2 for show the Data in Queue \n3 for
Delete the data from the Queue\n0 for Exit");
scanf("%d",&opt);
switch(opt)
{
case 1:
printf("\nEnter the number of data");
scanf("%d",&n);
printf("\nEnter your data");
i=0;
while(i<n)
{
scanf("%d",&data);

42
DATA STRUCTURE LAB

enqueue(data); i++;
}
break;
case 2: print();
break;
case 3 :dequeue();
break;
case 0: break;
default : printf(“\n incorrect
choice”);
}
}while(opt!=0);
return 0
}

OUTPUT

43
DATA STRUCTURE LAB

Program 9:Given S1=”Flowers”, S2=”are beautiful”


a. Find the length of S1.
b. Concatenate S1 and S2.
c. Extract the substring “low” from S1. d. Find “are” in S2 and replace it with “is”.

FLOW CHART

44
DATA STRUCTURE LAB

ALGORITHM

For finding length of two string:


Step1: Create an empty string named result
Step2: Add all the characters of first string to the string result Step3: Add all the characters of
second string to the string result Step4:result contains the concatenation of input strings.

For concatenate 2 strings:


Step1:Get the two Strings to be concatenated
Step2:Declare a new Strings to store the concatenated String
Step3:Insert the first string in the new string
Step4:Insert the second string in the new string
Step5:Print the concatenated string

SOURCE CODE

#include<stdio.h>
#include<string.h>
#include<conio.h>
#define substr
45
DATA STRUCTURE LAB

void replaceSubstring(char [],char[],char[]);

void main()
{

char string1[50]="flowers",string2[50]="are beautiful",sub[30]="low",replace_str[30]="are",new_str[50]="is";

int len;
clrscr();
printf("\nLength of string 1 is :%d",strlen(string1));

printf("\n conctenation of two strings :

%s",strcat(string1,string2));
printf("\n sub string %s found at loc %d",sub,substr(string1,2,3));
replaceSubstring(string2,replace_str,new_str);
printf("\nThe string after replacing : %s\n",string2);
getch();
}

voidreplaceSubstring(char string[],char sub[],char new_str[])


{
int stringLen,subLen,newLen;
int i=0,j,k;
int flag=0,start,end;
stringLen=strlen(string);

subLen=strlen(sub);
newLen=strlen(new_str);

for(i=0;i<stringLen;i++)
{
flag=0;
start=i;
for(j=0;string[i]==sub[j];j++,i++)
if(j==subLen-1) flag=1;
end=i;
if(flag==0) i-=j;

else
{
for(j=start;j<end;j++)
{
46
DATA STRUCTURE LAB

for(k=start;k<stringLen;k++) string[k]=string[k+1];
stringLen--;
i--;
}

for(j=start;j<start+newLen;j++)
{
for(k=stringLen;k>=j;k--)
string[k+1]=string[k];
string[j]=new_str[j-start];
stringLen++;
i++;
}
}
}
}

OUTPUT

47
DATA STRUCTURE LAB

Program 10 : : Write a program to convert an infix expression X^y/(5*z)+2


to its postfix expression.

FLOW CHART

48
DATA STRUCTURE LAB

49
DATA STRUCTURE LAB

ALGORTHIM

Step 1 : Scan the Infix Expression from left to right.


Step 2 : If the scanned character is an operand, append it with final Infix to Postfix string.
Step 3 : Else,
Step 3.1 : If the precedence order of the scanned(incoming) operator is greater than the precedence order of the operator
in the stack (or the stack is empty or the stack contains a ‘(‘ or ‘[‘ or ‘{‘), push it on stack.
Step 3.2 : Else, Pop all the operators from the stack which are greater than or equal to in precedence than that of the
scanned operator. After doing that Push the scanned operator to the stack. (If you encounter parenthesis while popping
then stop there and push the scanned operator in the stack.)
Step 4 : If the scanned character is an ‘(‘ or ‘[‘ or ‘{‘, push it to the stack.
Step 5 : If the scanned character is an ‘)’or ‘]’ or ‘}’, pop the stack and and output it until a ‘(‘ or ‘[‘ or ‘{‘ respectively
is encountered, and discard both the parenthesis.
Step 6 : Repeat steps 2-6 until infix expression is scanned.
Step 7 : Print the output
Step 8 : Pop and output from the stack until it is not empty.

SOURCE CODE

#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<string.h>
#definemax20
Void push(charelement);
Intpop();
Intpreced(charelement);
Chars[max];
Inttop=0;
Voidmain()
{
int i=0,j=0;
char ch,element;
char infix[max],post[max];
clrscr();
printf("\n\tEnteravalidinfixExpression:");
scanf("%s",&infix);
push('#');
for(i=0;i<strlen(infix);i++)
{
50
DATA STRUCTURE LAB

ch=infix[i];
if(isalnum(ch))
post[j++]=ch;
else
{
if(ch=='(')
push(ch);
else if(ch==')')
{
while(s[top]!='(') post[j++]=pop();
element=pop();
printf("%c",element);
}
else
{
while(preced(s[top])>=preced(ch))
post[j++]=pop();
push(ch);
}
}
}
while(s[top]!='#')

post[j++]=pop();
post[j]=NULL;
printf("\n\tResultantpostfixExpressionis:%s\n",post);
getch();
}
Intpreced(char element)
{
switch(element)
{
case'+':
case'-':return(1);
case'*':
case'/':return(2);
case'^':return(3);
case'(':
case'#':return(0);
}
return(0);
}
void push(char element)
{
s[++top]=element;
51
DATA STRUCTURE LAB

return;
}
int pop()
{
char element; element=s[top--];
return(element);
}

OUTPUT

52
DATA STRUCTURE LAB

Program 11 :
Write a program to evaluate a postfix expression 5 3 +8 2 - *.

FLOW CHART

53
DATA STRUCTURE LAB

ALGORITHM

Step1:Create a stack to store operands.


54
DATA STRUCTURE LAB

Step2: Scan the given expression from left to right.

Step3: a)If the scanned character is an operand, push it into the stack.

b)If the scanned character is an operator, POP 2 operands from stack and perform operation and PUSH the
result back to the stack.

Step4:Repeat step 3 till all the characters are scanned.

Step5:When the expression is ended, the number in the stack is the final result.

SOURCE CODE

#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<ctype.h>
#include<string.h>
#define max 20
int a[max],top=0;
int pop();
void push(int element);
Void main()
{
Char posfix[max],ch;
Int i,op1,op2,res;

clrscr();
printf("\n\t\tProgramtoEvalutepostfixExpression.");
printf("\n\t\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
printf("\nEnterthepostfixexpression:");
scanf("%s",&posfix);
for(i=0;i<strlen(posfix);i++)
{
ch=posfix[i];
if(isdigit(ch)) push(ch-'0');
else
{
op2=pop(); op1=pop(); switch(ch)
{
Case '+':res=op1+op2;
break;
case '-':res=op1-op2;
break;
case '*':res=op1*op2;
55
DATA STRUCTURE LAB

break;
case '/':res=op1/op2;
break;
case '^':res=pow(op1,op2);
break;
default :printf("\n Enter the valid option:");
}
push(res);
}

}
printf("Resultofaboveexpressionis:%d\n",pop());
getch();
}
void push(int element)
{
a[++top]=element;
}
int pop()
{
int element;
element=a[top--];
return(element);
}

OUTPUT

56
DATA STRUCTURE LAB

Program 12 : Write a program to create a binary tree with the elements


18,15,40,50,30,17,41 after creation insert 45 and 19 into tree and delete 15,17
and 41 from tree. Display the tree on each insertion and deletion operation.

FLOW CHART

ALGORITHM

Step1: Create a new BST node and assign values to it.


Step2: insert(node, key)
i) If root == NULL, return the new node to the calling function.
ii) if root=>data < key call the insert function with root=>right and assign the return value in root=>right.
root->right = insert(root=>right,key)
iii) if root=>data > key call the insert function with root->left and assign the return value in root=>left.

57
DATA STRUCTURE LAB

root=>left = insert(root=>left,key)
Step3: Finally, return the original root pointer to the calling function.

SOURCE CODE

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct node
{
int data;
struct node *left,*right;
};
struct node *root; void insert(int x)
{
struct node *p,*previous,*current;
p=(struct node *)malloc(sizeof(struct node));
if(p==NULL)
{
printf("\n Out of memory");
}
p->data=x;
p->left=NULL;
p->right=NULL;
if(root=NULL)
{
root=p;
return;
}
previous=NULL;
current=root;
while(current!=NULL)
{
previous=current;
if(p->data<current->data) current=current->left;
else
current=current->right;
}
if(p->data<previous->data) previous->left=p;

58
DATA STRUCTURE LAB

else
previous->right=p;

}
voidinorder(struct node *t)
{
if (t!=NULL)
{
inorder(t->left);
printf("\n %5d",t->data);
inorder (t->right);
}
}
void del(int x)
{
int tright=0,tleft=0;
struct node *ptr=root;
struct node *parent=root;
struct node *t1=root;
struct node *temp=root;
while(ptr!=NULL&&ptr->data!=x)
{
parent=ptr;
if (x<ptr->data)
ptr=ptr->left;
else
ptr=ptr->right;
}
if (ptr==NULL)
{
printf("\n Delete element not found");
return ;
}
else if(t1->data==x && (t1->left ==NULL || t1-
>right==NULL))
if(t1->left==NULL) t1=t1->right;
else
t1=t1->left;
else if (ptr->left==NULL)
if (x<parent->data)
parent->left=ptr->right;
else
parent->right=ptr->right;
else if (ptr->right==NULL)
59
DATA STRUCTURE LAB

if (x<parent->data)
parent->left=ptr->left;
else
parent->right=ptr->left;
else
{
temp=ptr;
parent=ptr;
if((ptr->left)>=(ptr->right))
{
ptr=ptr->left;
while(ptr->right!=NULL)
{
tright=1;
parent=ptr;
ptr=ptr->right;
}
temp->data=ptr->data;
if(tright)
parent->right=ptr->left;
else
parent->left=ptr->left;
}
else
{
ptr=ptr->right;
while (ptr->left!=NULL)
{
tleft=1;
parent=ptr;
ptr=ptr->left;
}
temp->data=ptr->data;
if(tleft)
parent->left=ptr->right;
else
parent->right=ptr->right;
}
free(ptr);

}
}

void main()
{
60
DATA STRUCTURE LAB

intop,n,srchno;
root=(struct node *)malloc(sizeof(struct node));
root->data=30;
root->right=root->left=NULL;
clrscr();
do
{
printf("\n 1.Insertion");
printf("\n 2.Deletion");
printf("\n 3.Inorder");
printf("\n 4.Quit");
printf("\n Enter your choice\n");
scanf("%d",&op);

switch (op)
{
case 1: printf("\n Enter the element to insert\n");
scanf("%d",&n);
insert(n);
break;
case 2: printf("\n Enter the element to be deleted\n");
scanf("%d",&srchno);
del(srchno);
break;
case 3: printf("\n The inorder elements are\n");
inorder(root);
getch();
break;
default: exit(0);
}
}while(op<4);
getch();

OUTPUT

1 5

61
DATA STRUCTURE LAB

0 3 9

0123569

62
DATA STRUCTURE LAB

Program 13 : Write a program to create binary search tree with the elements {2,5,1,3,9,0,6} and
perform inorder, preorder and post order traversal.

FLOW CHART

63
DATA STRUCTURE LAB

ALGORITHM

For creating node:


Step1:Create a new BST node and assign values to it.
Step2:insert(node, key)
i) If root == NULL, return the new node to the calling function.
ii) if root=>data < key call the insert function with root=>right and assign the return value in
root=>right.
root->right = insert(root=>right,key)
iii) if root=>data > key call the insert function with root->left and assign the return value in root=>left.
root=>left = insert(root=>left,key)
Step3:Finally, return the original root pointer to the calling function.

Preorder Traversal:
Step1:Visit or print the root.
Step2:Traverse the left sub tree.
Step3:Traverse the right sub tree.

Postorder Traversal:
Step1:Traverse the left sub tree.
Step2:Traverse the right sub tree.
Step3:Visit or print the root.

Inorder Traversal:
Step1:Traverse the left sub tree.
Step2:Visit or print the root.
Step3:Traverse the right sub tree.

SOURCE CODE
64
DATA STRUCTURE LAB

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct node
{
struct node *left;
int info;
struct node *right;
};
void insert(struct node**,int);
void inorder(struct node *);
void postorder(struct node *);
void preorder(struct node *);
void main()
{
struct node *ptr;
int n,i,item,ch;
ptr=NULL;
clrscr();
while(1)
{
printf("\nbinary search tree");
printf("\n1.creation of bst");
printf("\n2.prorder traversal");
printf("\n3.inorder traversal");
printf("\n4.postorder traversal");
printf("\n5.exit");
printf("\n enter your choice");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("enter number of terms to add to tree");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("enter the element:");
scanf("%d",&item);

65
DATA STRUCTURE LAB

insert(&ptr,item);
}
break;
case 2:printf("preorder traversal");
preorder(ptr);
break;
case 3: printf("inorder traversal");
inorder(ptr);
break;
case 4:printf("postorder traversal");
postorder(ptr);
break;
case 5:exit(0);
}
}
}
void insert(struct node **p,int item)
{
if((*p)==NULL)
{
printf("\n node created\n");
(*p)=malloc(sizeof(struct node));
(*p)->left=NULL;
(*p)->right=NULL;
(*p)->info=item;
return;
}
else
if(item<(*p)->info)
{
printf("\n directed to left link");
insert(&((*p)->left),item);
}
else
if(item==(*p)->info)
{
printf("key found!!value rejected");
return;

66
DATA STRUCTURE LAB

}
else
{
printf("\n directed to right link");
insert(&((*p)->right),item);
}
return;
}
void inorder(struct node *p)
{
if(p!=NULL)
{
inorder(p->left);
printf("\n%d",p->info);
inorder(p->right);
}
else
return;
}
void preorder(struct node *p)
{
if(p!=NULL)
{
printf("\n%d",p->info);
preorder(p->left);
preorder(p->right);
}
else
return;
}
void postorder(struct node *p)
{
if(p!=NULL)
{
postorder(p->left);
postorder(p->right);
printf("\n%d",p->info);
}

67
DATA STRUCTURE LAB

else
return;
}

68
DATA STRUCTURE LAB

Program 14: : Write a program to sort the following elements using heap sort
{9,16,32,8,4,1,5,8,0}.

FLOW CHART

69
DATA STRUCTURE LAB

ALGORITHM
HEAP_SORT(ARR, N)

70
DATA STRUCTURE LAB

Step 1: [Build Heap H] Repeat for i=0 to N-1


CALL INSERT_HEAP(ARR, N, ARR[i])
[END OF LOOP]

Step 2: Repeatedly Delete the root element Repeat while N > 0


CALL Delete_Heap(ARR,N,VAL)
SET N = N+1
[END OF LOOP]

Step 3: END

SOURCE CODE

#include<stdio.h>
#include<conio.h>
void heap(int a[],int n)
{
inti,j,k,item;
for(k=1;k<n;k++)
{
item=a[k];
i=k;
j=(i-1)/2;
while(i>0&&item>a[j])
{
a[i]=a[j];

i=j;
j=(i-1)/2;
}
a[i]=item;
}
}
void adjust(int a[],int n)
{
inti,j,item;
j=0;
item=a[j];
i=2*j+1;
while(i<=n-1)
{
if(i+1<=n-1)
if(a[i]<a[i+1])i++; if(item<a[i])
{
71
DATA STRUCTURE LAB

a[j]=a[i]; j=i; i=2*j+1;


}
else
break;

}
a[j]=item;
}
voidheapsort(int a[],int n)
{
inti,temp; heap(a,n); for(i=n-1;i>0;i--)
{
temp=a[0]; a[0]=a[i]; a[i]=temp; adjust(a,i);
}
}

void main()

{
int a[20],i,n,temp; clrscr();
printf("\n\n\tEnter number of elements to sort:");
scanf("%d",&n);
printf("\n\tEnter the elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
heapsort(a,n);
printf("\n\tThe sorted List:");
for(i=0;i<n;i++)
printf("%d ",a[i]);
getch();
}

OUTPUT

72
DATA STRUCTURE LAB

73 | P a g e
DATA STRUCTURE LAB

74 | P a g e

You might also like