ds lab.pdf - gokaraju rangaraju institute of engineering and

150
Q Gokaraju Rangaraju Institute of Engineering & Technology Department of MCA Y. Sri Lalitha T. Anusha Bhakti Barhate Data Structure Using JAVA LAB Manual MCA II yr II Sem

Upload: others

Post on 25-Mar-2022

9 views

Category:

Documents


0 download

TRANSCRIPT

Q

Gokaraju Rangaraju

Institute of Engineering & Technology

Department of MCA

Y. Sri Lalitha

T. Anusha

Bhakti Barhate

Data Structure Using JAVA

LAB Manual

MCA II yr II Sem

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 2

Appendix

Syllabus…………………………………………………… 2

Contents…………………………………………………... 3

Additional program………………………………………. 108

Syllabus

DATA STRUCTURES LAB

List of Sample Problems/Experiments:

1. Write a JAVA/C++ program to perform the following operations :

a) Create a SLL of integers. b) Delete an integer from SLL.

2. Write a JAVA/C++ program to perform the following operations:

a) Create a DLL of integers. b) Delete an integer from DLL.

3. Write JAVA/C++ programs to implement the following using an array.

a) Stack ADT b) Queue ADT

4. Write JAVA/C++ programs to implement the following using a singly linked list.

a) Stack ADT b) Queue ADT

5. Write a JAVA/C++ program to convert a given infix expression into postfix form using stack.

6. Write a JAVA/C++ programs to implement the deque (double ended queue) ADT using DLL

and an array.

7. Write a JAVA/C++ programs that use recursive functions to traverse the given binary tree in

a) Preorder b) inorder and c) postorder

8. Write a JAVA/C++ programs that use non-recursive functions to traverse the given binary tree

in a) Preorder b) inorder and c) post order.

9. Write a JAVA/C++ program to perform the following operations:

a) Insert an element into a BST

b) Delete an element from a BST

c) Search for a key element in a BST

10.Write JAVA/C++ programs to Implement BFS and DFS of a given graph.

11.Write JAVA/C++ programs to Implementing Linear and Binary Search methods.

12. Write JAVA/C++ programs to implement the following Sorting methods

a) Bubble Sort b) Selection Sort c) Insertion Sort

d) Merge Sort e) Quick Sort f) Heap Sort

13. Write a JAVA/C++ program to insert and delete an element from B-tree

14. Write a JAVA/C++ program to insert and delete an element from an AVL-tree.

15. Write a JAVA/C++ program to implement all the functions of a dictionary (ADT) using

hashing.

16. Write a JAVA/C++ program for generating Minimum cost spanning tree using Kruskal‟s

algorithm.

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 3

Contents

1. Write a JAVA/C++ program to perform the following operations :

a. Create a SLL of integers

b. Delete an integer from SLL…………………………………………... 5

2. Write a JAVA/C++ program to perform the following operations:

a. Create a DLL of integers

b. Delete an integer from DLL…………………………………………... 15

3. Write JAVA/C++ programs to implement the following using an array.

a. Stack ADT……………………………………………………………... 26

b. Queue ADT…………………………………………………………….. 30

4. Write JAVA/C++ programs to implement the following using

a singly linked list.

a. Stack ADT………………………………………………………………. 33

b. Queue ADT………………………………………………………………35

5. Write a JAVA/C++ program to convert a given infix expression

into postfix form using stack…………………………………………………………39

6. Write a JAVA/C++ programs to implement the deque

(double ended queue) ADT using DLL and an array……………………………… ..42

7. Write a JAVA/C++ programs that use recursive functions to traverse

the given binary tree in

a) Preorder b) inorder and c) postorder……………………………………...47

8. Write a JAVA/C++ programs that use non-recursive functions to traverse

the given binary tree in

a) Preorder b) inorder and c) post order…………………………………… 53

9. Write a JAVA/C++ program to perform the following operations:

a) Insert an element into a BST

b) Delete an element from a BST

c) Search for a key element in a BST ……………………………………….. 59

10. Write JAVA/C++ programs to Implement BFS and DFS of a given graph……… … 69

11. Write JAVA/C++ programs to Implementing Linear and

Binary Search methods……………………………………………………………… 81

12. Write JAVA/C++ programs to implement the following Sorting methods

a) Bubble Sort b) Selection Sort c) Insertion Sort

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 4

d) Merge Sort e) Quick Sort f) Heap Sort……………………………………. 86

13. Write a JAVA/C++ program to insert and delete an element from B-tree

14. Write a JAVA/C++ program to insert and delete an element from an

AVL-tree. …………………………………………………………………………….. 97

15. Write a JAVA/C++ program to implement all the functions of

a dictionary (ADT) using hashing……………………………………………………..102

16. Write a JAVA/C++ program for generating Minimum cost spanning

tree using Kruskal‟s algorithm

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 5

1. Write a JAVA/C++ program to perform the following operations :

a) Create a SLL of integers. b) Delete an integer from SLL.

import java.io.*;

class sll

{

int data;

sll next,first,last;

sll()

{

data=0;

next=null;

}

sll (int d)

{

data=d;

next=null;

}

sll(int d,sll sll)

{

data=d;

next=sll;

}

boolean isEmpty()

{

if(first==null)

return true;

return false;

}

int size()

{

sll ptr;

int count=0;

for(ptr=first;ptr!=null;ptr=ptr.next)

{

count++;

}

return count;

}

boolean isFirst(sll node)

{

if(first==node)

return true;

return false;

}

boolean isLast(sll node)

{

if(last==node)

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 6

return true;

return false;

}

void display()

{

sll ptr;

if(!isEmpty())

{

for(ptr=first;ptr.next!=null;ptr=ptr.next)

System.out.print(ptr.data+"->");

System.out.print(ptr.data);

}

else

System.out.println("list is empty");

}

void insertatbegin(int item)

{

sll nn=new sll(item);

if(first==null)

{

first=last=nn;

}

else{

nn.next=first;

first=nn;}

}

void insertatend(int item)

{

sll nn=new sll(item);

if(last==null){

first=last=nn;}

else{

last.next=nn;

last=nn;}

}

sll search(int key)

{

sll ptr=null;

for(ptr=first;ptr!=null;ptr=ptr.next)

{

if(ptr.data==key)

break;

}

return ptr;

}

void insertb4key(int item,int key)

{

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 7

sll psll1,nn;

nn=new sll(item);

psll1=search(key);

sll psll=getprev(psll1);

if(psll!=null)

{

nn.next=psll.next;

psll.next=nn;

}

else if(psll==null&&first.data==key)

{

nn.next=first;

first=nn;

}

else

System.out.println("key not found");

}

void insertafterkey(int item,int key)

{

sll psll,nn;

nn=new sll(item);

psll=search(key);

if(psll!=null)

{

nn.next=psll.next;

psll.next=nn;

}

else

System.out.println("key not found");

}

int deleteatfirst()

{

int k;

if(first!=null)

{

k=first.data;

if(first.next==null)

{first=last=null;}

else

first=first.next;

return k;

}

else

{

System.out.println("list is empty");

return -1;}

}

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 8

int deleteatlast()

{

int k;

sll ptr;

if(first!=null){

if(first!=null&&first!=last)

{

for(ptr=first;ptr.next!=last;ptr=ptr.next);

if(ptr!=null){

k=last.data;

ptr.next=null;

last=ptr;

return k;}

}

else if(first==last)

{

k=last.data;

first=last=null;

return k;

}

}

else

{

System.out.println("list is empty");

return -1;

}

return -1;

}

int deletekey(int key)

{

sll ptr,prev=null;

if(first!=null)

{

ptr=search(key);

if(ptr==first)

{

first=first.next;

return ptr.data;

}

prev=getprev(ptr);

if(ptr!=null&&prev!=null)

{

prev.next=ptr.next;

return ptr.data;

}

else if(ptr!=null&&prev==null)

{

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 9

first=first.next;

return first.data;

}

}

else

System.out.println("prev not exist");

return -1;

}

void swap(int i,int j)

{

sll ptr1=search(i);

sll ptr2=search(j);

int temp;

if(ptr1!=null&&ptr2!=null){

temp=ptr1.data;

ptr1.data=ptr2.data;

ptr2.data=temp;}

else

System.out.println("key not found");

}

void replace(sll n,int key)

{

n.data=key;

}

sll getprev(sll node)

{

sll prev=null;

for(prev=first;prev.next!=node;prev=prev.next);

return prev;

}

sll getnext(sll n)

{

sll ptr;

for(ptr=first;ptr.next!=null;ptr=ptr.next)

{

if(n.next==ptr.next)

break;

}

return ptr.next;

}

void swapnode(int p,int q)

{

sll n1,n2,prev1,prev2;

n1=search(p);

n2=search(q);

prev1=getprev(n1);

prev2=getprev(n2);

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 10

sll temp=new sll();

if(prev1==null)

{

temp.next=n2.next;

n2.next=n1.next;

n1.next=temp.next;

prev2.next=n1;

first=n2;

}

else

{

prev1.next=n2;

prev2.next=n1;

temp.next=n2.next;

n2.next=n1.next;

n1.next=temp.next;

}

}

void create(int n)

{

sll nn;

for(int i=1;i<=n;i++)

{

nn=new sll(i*10);

if(first==null)

{

first=last=nn;

}

else{

last.next=nn;

last=nn;}

}

}

void traverse()

{

sll ptr;

int count=0;

for(ptr=first;ptr!=null;ptr=ptr.next)

{

count++;

}

System.out.println(count+" nodes are visited");

}

public static void main(String args[])throws Exception

{

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 11

sll obj=new sll();

int ch;

do

{

System.out.println("\n--------menu--------");

System.out.println("1.create list");

System.out.println("2.search key");

System.out.println("3.isEmpty ");

System.out.println("4.size");

System.out.println("5.isFirst");

System.out.println("6.isLast");

System.out.println("7.getprevious");

System.out.println("8.getnext");

System.out.println("9.insertAtBegin");

System.out.println("10.insertAtEnd");

System.out.println("11.insertb4key");

System.out.println("12.insertafter key");

System.out.println("13.deleteAtbegin");

System.out.println("14.deleteAtEnd");

System.out.println("15.deleteKey");

System.out.println("16.swap elements");

System.out.println("17.replace\n");

System.out.println("18.swap nodes");

System.out.println("19.traverse");

System.out.print("enter ur choice:");

ch=Integer.parseInt(br.readLine());

switch(ch)

{

case 1:System.out.println("enter n value:");

int n=Integer.parseInt(br.readLine());

obj.create(n);

obj.display();

break;

case 2:System.out.println("enter element");

int key1=Integer.parseInt(br.readLine());

System.out.println(obj.search(key1));

break;

case 3:System.out.println(obj.isEmpty());

break;

case 4:System.out.println(obj.size());

break;

case 5:System.out.print("enter element:");

int key2=Integer.parseInt(br.readLine());

sll node=obj.search(key2);

System.out.println(obj.isFirst(node));

break;

case 6:System.out.print("enter element:");

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 12

int key3=Integer.parseInt(br.readLine());

sll node1=obj.search(key3);

System.out.println(obj.isLast(node1));

break;

case 7:System.out.print("enter element:");

int key4=Integer.parseInt(br.readLine());

sll ptr1=obj.search(key4);

sll sa=obj.getprev(ptr1);

if(sa!=null)

System.out.println(sa.data);

else

System.out.println("no node existed");

break;

case 8:System.out.print("enter element:");

int key5=Integer.parseInt(br.readLine());

sll ptr2=obj.search(key5);

sll gn1=obj.getnext(ptr2);

if(gn1!=null)

System.out.println(gn1.data);

else

System.out.println("no node existed");

break;

case 9:System.out.print("which element do u want to insert :");

int n1=Integer.parseInt(br.readLine());

obj.insertatbegin(n1);

break;

case 10:System.out.print("which element do u want to insert :");

int n2=Integer.parseInt(br.readLine());

obj.insertatend(n2);

break;

case 11:if(!obj.isEmpty())

{

System.out.print("which element do u want to insert :");

int item=Integer.parseInt(br.readLine());

System.out.print("which element before u want to insert :");

int key=Integer.parseInt(br.readLine());

obj.insertb4key(item,key);

obj.display();

}

else

System.out.println("list is empty");

break;

case 12:if(!obj.isEmpty())

{

System.out.print("which element do u want to insert :");

int item1=Integer.parseInt(br.readLine());

System.out.print("which element after u want to insert :");

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 13

int ky=Integer.parseInt(br.readLine());

obj.insertafterkey(item1,ky);

obj.display();

}

else

System.out.println("list is empty");

break;

case 13:if(!obj.isEmpty())

{

obj.deleteatfirst();

obj.display();

}

else

System.out.println("list is empty");

break;

case 14:if(!obj.isEmpty())

{

obj.deleteatlast();

obj.display();

}

else

System.out.println("list is empty");

break;

case 15:System.out.println("which element do u want to delete:");

int key6=Integer.parseInt(br.readLine());

if(!obj.isEmpty())

{

obj.deletekey(key6);

obj.display();

}

else

System.out.println("list is empty");

break;

case 16:if(!obj.isEmpty())

{

System.out.println("enter 2 elements which u want to swap");

int key7=Integer.parseInt(br.readLine());

int key8=Integer.parseInt(br.readLine());

obj.swap(key7,key8);

obj.display();

}

else

System.out.println("list is emty");

break;

case 17:if(!obj.isEmpty())

{

System.out.print("find:");

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 14

int find=Integer.parseInt(br.readLine());

System.out.print("replace with:");

int replace=Integer.parseInt(br.readLine());

sll sl=obj.search(find);

if(sl!=null)

{

obj.replace(sl,replace);

}

else

System.out.println(" element not found");

obj.display();

}

else

System.out.println("list is empty");

break;

case 18:if(!obj.isEmpty()){

System.out.println("enter 2 elements which u want to swap");

int key11=Integer.parseInt(br.readLine());

int key12=Integer.parseInt(br.readLine());

obj.swap(key11,key12);

obj.display();

}

else

System.out.println("list is empty");

break;

case 19:obj.traverse();

break;

}

}while(ch!=0);

}

}

Output:

Insert

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 15

Delete:

2) Write a JAVA/C++ program to perform the following operations:

a) Create a DLL of integers. b) Delete an integer from DLL.

import java.io.*;

class Dll

{

int data;

Dll prev,next,first,last;

Dll()

{

data=0;

prev=next=null;

}

Dll(int d)

{

data=d;

prev=next=null;

}

int size()

{

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 16

Dll ptr;

int count=0;

for(ptr=first;ptr!=null;ptr=ptr.next)

{

count++;

}

return count;

}

boolean isEmpty()

{

if(first==null)

return true;

return false;

}

Dll search(int key)

{

Dll ptr;

for(ptr=first;ptr!=null;ptr=ptr.next)

{

if(ptr.data==key)

break;

}

return ptr;

}

boolean isfirst(Dll node)

{

if(first==node)

return true;

return false;

}

Dll getfirst()

{

return first;

}

Dll getlast()

{

Dll ptr;

for(ptr=first;ptr.next!=null;ptr=ptr.next);

return ptr;

}

int getposition(Dll node)

{

int count=0;

for(Dll ptr=first;ptr!=null;ptr=ptr.next)

{

count++;

if(ptr==node)

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 17

break;

}

return count;

}

Dll getprev(Dll node)

{

Dll ptr,prev=null;

for(ptr=first;ptr!=node;ptr=ptr.next);

if(ptr!=first)

return ptr.prev;

else

return prev;

}

Dll getnext(Dll node)

{

Dll ptr,next=null;

for(ptr=first;ptr!=node;ptr=ptr.next);

if(ptr.next!=null)

return ptr.next;

else

return next;

}

Dll insertbeforenode(Dll node,int key2)

{

Dll nn=new Dll(key2);

if(first!=node)

{

nn.next=node;

nn.prev=node.prev;

nn.next.prev=nn;

nn.prev.next=nn;

}

else

{

nn.next=first;

first.prev=nn;

first=nn;

}

return nn;

}

Dll insertafternode(Dll node,int item)

{

Dll nn=new Dll(item);

if(node.next!=null)

{

nn.prev=node;

nn.next=node.next;

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 18

nn.prev.next=nn;

nn.next.prev=nn;

}

else

{

nn.prev=node;

node.next=nn;

}

return nn;

}

Dll insertfirst(int item)

{

Dll nn=new Dll(item);

if(!isEmpty())

{

first.prev=nn;

nn.next=first ;

first=nn;

}

else

{

first=nn;

}

return nn;

}

Dll insertlast(int item)

{

Dll ptr;

Dll nn=new Dll(item);

if(!isEmpty())

{

for(ptr=first;ptr.next!=null;ptr=ptr.next);

nn.prev=ptr;

ptr.next=nn;

}

else

{

first=nn;

}

return nn;

}

int deletekey(int key)

{

Dll ptr;

ptr=search(key);

if(ptr==first)

first=first.next;

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 19

else if(ptr==null)

{

System.out.println("delete failed as key not found");

return -1;

}

else

{

ptr.prev.next=ptr.next;

if(ptr.next!=null)

ptr.next.prev=ptr.prev;

}

return ptr.data;

}

int deletenode(Dll node)

{

Dll ptr;

if(node!=null)

{

int k=node.data;

if((node==first) && (node.next !=null))

{

first=node.next;

first.prev=null;

return k;

}

else if((node.next==null) && (node.prev!=null))

{

node.prev.next=null;

return k;

}

else if(node.prev==null&&node.next==null)

{

System.out.println(node.data + " " + node.prev );

first=null;

return k;

}

else

{

node.prev.next=node.next;

node.next.prev=node.prev;

return k;

}

}

else

{System.out.println("Node not found");

return -1;

}

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 20

}

void swapElements(int item1,int item2)

{

Dll node1=search(item1);

Dll node2=search(item2);

if(node1!=null&&node2!=null)

{

int t;

t=node1.data;

node1.data=node2.data;

node2.data=t;

}

else

System.out.println("swap not possible");

}

int replaceElement(Dll node,int item)

{

if(node!=null)

{

int t=node.data;

node.data=item;

return t;

}

else

return -1;

}

void traversal()

{

Dll ptr;

int c=0;

for(ptr=first;ptr!=null;ptr=ptr.next)

{

c++;

}

System.out.print(c+" nodes are visited");

}

void create(int n)

{

Dll ptr,nn;

for(int i=1;i<=n;i++)

{

nn=new Dll(i*10);

if(first==null)

{

first=nn;

}

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 21

else if(first.next==null)

{

first.next=nn;

nn.prev=first;

}

else{

for(ptr=first;ptr.next!=null;ptr=ptr.next);

ptr.next=nn;

nn.prev=ptr;

}

}

}

void display()

{

Dll ptr;

if(!isEmpty())

{

for(ptr=first;ptr.next!=null;ptr=ptr.next)

System.out.print(ptr.data+"->");

System.out.print(ptr.data);

}

else

System.out.println("list is empty");

}

public static void main(String args[])throws Exception

{

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

Dll obj=new Dll();

int ch;

do

{

System.out.println();

System.out.println("============MENU============");

System.out.println("1.create list");

System.out.println("2.size");

System.out.println("3.isEmpty");

System.out.println("4.isfirst");

System.out.println("5.getfirst");

System.out.println("6.getlast");

System.out.println("7.getposition");

System.out.println("8.search");

System.out.println("9.getprev");

System.out.println("10.getnext");

System.out.println("11.insert b4 node: ");

System.out.println("12.insert after node: ");

System.out.println("13.insert first ");

System.out.println("14.insert last ");

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 22

System.out.println("15.delete key ");

System.out.println("16.delete node ");

System.out.println("17.swap elements ");

System.out.println("18.replace element");

System.out.println("19.traversal");

System.out.println("==========================");

System.out.print("enter ur choice:");

ch=Integer.parseInt(br.readLine());

switch(ch)

{

case 1:System.out.print("enter n value: ");

int n=Integer.parseInt(br.readLine());

obj.create(n);

obj.display();

break;

case 2:int size =obj.size();

System.out.println("size of list is:"+size);

break;

case 3:System.out.println(obj.isEmpty());

break;

case 4:System.out.print("enter element: ");

int e1=Integer.parseInt(br.readLine());

if(!obj.isEmpty())

{

Dll node1=obj.search(e1);

System.out.println(obj.isfirst(node1));

}

else

System.out.println("list is empty");

break;

case 5:if(!obj.isEmpty())

{

Dll ptr1=obj.getfirst();

System.out.println("first element is: "+ptr1.data);

}

else

System.out.println("list is empty");

break;

case 6:if(!obj.isEmpty())

{

Dll ptr2=obj.getlast();

System.out.println("last element is: "+ptr2.data);

}

else

System.out.println("list is empty");

break;

case 7:System.out.print("enter element: ");

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 23

int e2=Integer.parseInt(br.readLine());

if(!obj.isEmpty())

{

Dll node2=obj.search(e2);

int pos=obj.getposition(node2);

System.out.println("position of the element: "+pos);

}

else

System.out.println("list is empty");

break;

case 8:System.out.print("enter element: ");

int e3=Integer.parseInt(br.readLine());

if(!obj.isEmpty())

{

Dll node3=obj.search(e3);

if(node3!=null)

System.out.println("key found");

else

System.out.println("key not found");

}

else

System.out.println(" list is empty");

break;

case 9:System.out.print("enter element: ");

int e4=Integer.parseInt(br.readLine());

if(!obj.isEmpty())

{

Dll node4=obj.search(e4);

Dll prev1=obj.getprev(node4);

if(prev1!=null)

System.out.println("previous node data is: "+prev1.data);

else

System.out.println("previous node not found");

}

else

System.out.println("list is empty");

break;

case 10:System.out.print("enter element: ");

int e5=Integer.parseInt(br.readLine());

if(!obj.isEmpty())

{

Dll node5=obj.search(e5);

Dll next1=obj.getnext(node5);

if(next1!=null)

System.out.println("next node data is: "+next1.data);

else

System.out.println("next node not found");

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 24

}

else

System.out.println("list is empty");

break;

case 11:System.out.print("which element before do u want to insert: ");

int e6=Integer.parseInt(br.readLine());

System.out.print("enter element do u want to insert: ");

int item=Integer.parseInt(br.readLine());

if(!obj.isEmpty())

{

Dll node6=obj.search(e6);

Dll node7=obj.insertbeforenode(node6,item);

System.out.println(node7.data+" is inserted");

obj.display();

}

else

System.out.println("list is empty");

break;

case 12:System.out.print("which element after do u want to insert: ");

int e7=Integer.parseInt(br.readLine());

System.out.print("enter element do u want to insert: ");

int item1=Integer.parseInt(br.readLine());

if(!obj.isEmpty())

{

Dll node8=obj.search(e7);

Dll node9=obj.insertafternode(node8,item1);

System.out.println(node9.data+" is inserted");

obj.display();

}

else

System.out.println("list is empty");

break;

case 13:System.out.print("enter element: ");

int ele=Integer.parseInt(br.readLine());

Dll dnode=obj.insertfirst(ele);

System.out.println(dnode.data+" is inserted");

obj.display();

break;

case 14:System.out.print("enter element: ");

int ele1=Integer.parseInt(br.readLine());

Dll dnode1=obj.insertlast(ele1);

System.out.println(dnode1.data+" is inserted");

obj.display();

break;

case 15:if(!obj.isEmpty())

{

System.out.print("Which element you want to delete: ");

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 25

int ele2=Integer.parseInt(br.readLine());

int ele3=obj.deletekey(ele2);

if(ele3!=-1)

System.out.print("Deleted element is : "+ele3);

obj.display();

}

else

System.out.println("list is empty");

break;

case 16:if(!obj.isEmpty())

{

System.out.print("Which element you want to delete: ");

int ele4=Integer.parseInt(br.readLine());

Dll dnode2=obj.search(ele4);

int value=obj.deletenode(dnode2);

if(value!=-1)

System.out.println("deleted node data is :"+value);

obj.display();

}

else

System.out.println("list is empty");

break;

case 17:System.out.print("enter first element: ");

int ele5=Integer.parseInt(br.readLine());

System.out.print("enter 2nd element: ");

int ele6=Integer.parseInt(br.readLine());

if(!obj.isEmpty()){

obj.swapElements(ele5,ele6);

obj.display();

}

else

System.out.println("list is empty");

break;

case 18:System.out.print("enter element to replace: ");

int ele9=Integer.parseInt(br.readLine());

System.out.print("at which node do u want to replace: ");

int ele10=Integer.parseInt(br.readLine());

Dll dnode5=obj.search(ele10);

if(!obj.isEmpty())

{

int x=obj.replaceElement(dnode5,ele9);

if(x!=-1)

System.out.println("replaced element is "+x);

obj.display();

}

else

System.out.println("list is empty");

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 26

break;

case 19:obj.traversal();

break;

case 21:

obj.display();

break;

}

}while(ch!=0);

}

}

Output:

Insert:

Delete:

3. Write JAVA/C++ programs to implement the following using an array.

a) Stack ADT b) Queue ADT

a)stack ADT

import java.io.*;

class stackclass

{

int top,ele,stack[],size;

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 27

stackclass(int n)

{

stack=new int[n];

size=n;

top=-1;

}

void push(int x)

{

ele=x;

stack[++top]=ele;

}

int pop()

{

if(!isempty())

{

System.out.println("Deleted element is");

return stack[top--];

}

else

{

System.out.println("stack is empty");

return -1;

}

}

boolean isempty()

{

if(top==-1)

return true;

else

return false;

}

boolean isfull()

{

if(size>(top+1))

return false;

else

return true;

}

int peek()

{

if(!isempty())

return stack[top];

else

{

System.out.println("stack is empty");

return -1;

}

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 28

}

void size()

{

System.out.println("size of the stack is :"+(top+1));

}

void display()

{

if(!isempty())

{

for(int i=top;i>=0;i--)

System.out.print(stack[i]+" ");

}

else

System.out.println("stack is empty");

}

}class stacktest

{

public static void main(String args[])throws Exception

{

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.println("enter the size of stack");

int size=Integer.parseInt(br.readLine());

stackclass s=new stackclass(size);

int ch,ele;

do

{

System.out.println();

System.out.println("1.push");

System.out.println("2.pop");

System.out.println("3.peek");

System.out.println("4.size");

System.out.println("5.display");

System.out.println("6.is empty");

System.out.println("7.is full");

System.out.println("8.exit");

System.out.println("enter ur choise :");

ch=Integer.parseInt(br.readLine());

switch(ch)

{

case 1:if(!s.isfull())

{

System.out.println("enter the element to insert: ");

ele=Integer.parseInt(br.readLine());

s.push(ele);

}

else

{

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 29

System.out.print("stack is overflow");

}

break;

case 2:int del=s.pop();

if(del!=-1)

System.out.println(del+" is deleted");

break;

case 3:int p=s.peek();

if(p!=-1)

System.out.println("peek element is: "+p);

break;

case 4:s.size();

break;

case 5:s.display();

break;

case 6:boolean b=s.isempty();

System.out.println(b);

break;

case 7:boolean b1=s.isfull();

System.out.println(b1);

break;

}

}

while(ch!=0);

}

}

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 30

b)queue ADT

import java.util.*;

class queue

{

int front,rear;

int que[];

int max,count=0;

queue(int n)

{

max=n;

que=new int[max];

front=rear=-1;

}

boolean isfull()

{

if(rear==(max-1))

return true;

else

return false;

}

boolean isempty()

{

if(front==-1)

return true;

else

return false;

}

void insert(int n)

{

if(isfull())

System.out.println("list is full");

else

{

rear++;

que[rear]=n;

if(front==-1)

front=0;

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 31

count++;

}

}

int delete()

{

int x;

if(isempty())

return -1;

else

{

x=que[front];

que[front]=0;

if(front==rear)

front=rear=-1;

else

front++;

count--;

}

return x;

}

void display()

{

if(isempty())

System.out.println("queue is empty");

else

for(int i=front;i<=rear;i++)

System.out.println(que[i]);

}

int size()

{

return count;

}

public static void main(String args[])

{

int ch;

Scanner s=new Scanner(System.in);

System.out.println("enter limit");

int n=s.nextInt();

queue q=new queue(n);

do

{

System.out.println("1.insert");

System.out.println("2.delete");

System.out.println("3.display");

System.out.println("4.size");

System.out.println("enter ur choise :");

ch=s.nextInt();

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 32

switch(ch)

{

case 1:System.out.println("enter element :");

int n1=s.nextInt();

q.insert(n1);

break;

case 2:int c1=q.delete();

if(c1>0)

System.out.println("deleted element is :"+c1);

else

System.out.println("can't delete");

break;

case 3:q.display();

break;

case 4:System.out.println("queue size is "+q.size());

break;

}

}

while(ch!=0);

}

}

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 33

4) Write JAVA/C++ programs to implement the following using a singly linked list.

a. Stack ADT b.Queue ADT

a)stack ADT

import java.io.*;

class Stack

{

Stack top,next,prev;

int data;

Stack()

{

data=0;

next=prev=null;

}

Stack(int d)

{

data=d;

next=prev=null;

}

void push(int n)

{

Stack nn;

nn=new Stack(n);

if(top==null)

top=nn;

else

{

nn.next=top;

top.prev=nn;

top=nn;

}

}

int pop()

{

int k=top.data;

if(top.next==null){

top=null;

return k;}

else{

top=top.next;

top.prev=null;

return k;

}

}

boolean isEmpty()

{

if(top==null)

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 34

return true;

else

return false;

}

void display()

{

Stack ptr;

for(ptr=top;ptr!=null;ptr=ptr.next)

System.out.print(ptr.data+" ");

}

public static void main(String args[ ])throws Exception

{

int x;

int ch;

BufferedReader b=new BufferedReader(new InputStreamReader(System.in));

Stack a=new Stack();

do{

System.out.println("enter 1 for pushing");

System.out.println("enter 2 for poping");

System.out.println("enter 3 for isEmpty");

System.out.println("enter 4 for display");

System.out.println("Enter 0 for exit");

System.out.println("enter ur choice ");

ch=Integer.parseInt(b.readLine());

switch(ch)

{

case 1:System.out.println("enter element to insert");

int e=Integer.parseInt(b.readLine());

a.push(e);

break;

case 2:if(!a.isEmpty())

{

int p=a.pop();

System.out.println("deleted element is "+p);

}

else

{

System.out.println("stack is empty");

}

break;

case 3:System.out.println(a.isEmpty());

break;

case 4:if(!a.isEmpty())

{

a.display();

}

else

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 35

{

System.out.println("list is empty");

}

}

}while(ch!=0);

}

}

OUTPUT:

b. queue ADT

import java.io.*;

class Qlnk

{

Qlnk front,rear,next;

int data;

Qlnk()

{

data=0;

next=null;

}

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 36

Qlnk(int d)

{

data=d;

next=null;

}

Qlnk getFront()

{

return front;

}

Qlnk getRear()

{

return rear;

}

void insertelm(int item)

{

Qlnk nn;

nn=new Qlnk(item);

if(isEmpty())

{

front=rear=nn;

}

else

{

rear.next=nn;

rear=nn;

}

}

int delelm()

{

if(isEmpty())

{

System.out.println("deletion failed");

return -1;

}

else

{

int k=front.data;

if(front!=rear)

front=front.next;

else

rear=front=null;

return k;

}

}

boolean isEmpty()

{

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 37

if(rear==null)

return true;

else

return false;

}

int size()

{

Qlnk ptr;

int cnt=0;

for(ptr=front;ptr!=null;ptr=ptr.next)

cnt++;

return cnt;

}

void display()

{

Qlnk ptr;

if(!isEmpty())

{

for(ptr=front;ptr!=null;ptr=ptr.next)

System.out.print(ptr.data+" ");

}

else

System.out.println("q is empty");

}

public static void main(String arr[])throws Exception

{

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

Qlnk m=new Qlnk();

int ch;

do

{

System.out.println("enter 1 for insert");

System.out.println("enter 2 for deletion");

System.out.println("enter 3 for getFront");

System.out.println("enter 4 for getRear");

System.out.println("enter 5 for size");

System.out.println("enter 6 for display");

System.out.println("enter 0 for exit");

System.out.println("enter ur choice");

ch=Integer.parseInt(br.readLine());

switch(ch)

{

case 1:System.out.println("enter ele to insert");

int item=Integer.parseInt(br.readLine());

m.insertelm(item);break;

case 2:int k=m.delelm();

System.out.println("deleted ele is "+k);break;

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 38

case 3:System.out.println("front index is"+(m.getFront()).data);break;

case 4:System.out.println("rear index is"+(m.getRear()).data);break;

case 5:System.out.println("size is"+m.size());break;

case 6:m.display();break;

}

}while(ch!=0);

}

}

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 39

5. Write a JAVA/C++ program to convert a given infix expression into postfix form using

stack.

import java.lang.*;

import java.io.*;

import java.util.*;

class charstack

{

int top,size;

char stack[],ele;

charstack(int n)

{

size=n;

top=-1;

stack=new char[n];

}

void push(char x)

{

ele=x;

if(!isfull())

{

stack[++top]=ele;

}

else

System.out.println("stack is full");

}

char pop()

{

if(!isempty())

{

return stack[top--];

}

else

{

System.out.println("stack is empty");

return 'a';

}

}

boolean isempty()

{

if(top==-1)

return true;

else

return false;

}

boolean isfull()

{

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 40

if(top>size)

return true;

else

return false;

}

void display()

{

if(!isempty())

System.out.println("="+stack[top]);

else

System.out.println("stack is empty");

}

char peek()

{

return stack[top];

}

}

class iftopf

{

charstack cs;

char pf[];

iftopf()

{

cs=new charstack(50);

pf=new char[50];

}

boolean iop(char op)

{

if(op=='+'||op=='-'||op=='*'||op=='/'||op=='('||op==')'||op=='^'||op=='%')

return true;

else

return false;

}

int prec(char op)

{

if(op=='+'||op=='-')

return 1;

else if(op=='/'||op=='*')

return 2;

else if(op=='%'||op=='^')

return 3;

return 0;

}

void infixtop(String infix)

{

char isym;

int j=0;

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 41

char ir[]=infix.toCharArray();

for(int i=0;i<ir.length;i++)

{

isym=ir[i];

if(!iop(isym))

{

pf[j]=isym;

j++;

}

else

{

if(isym=='('||cs.isempty())

cs.push(isym);

else if(isym==')')

{

while(cs.peek()!='(')

{

pf[j]=cs.pop();

j++;

}

char v=cs.pop();

}

else if(cs.isempty())

cs.push(isym);

else if(cs.isempty()||cs.peek()=='('||(prec(cs.peek())<prec(isym)))

cs.push(isym);

else

{

while((!cs.isempty())&&(cs.peek()!='(')&&prec(cs.peek())>=prec(isym))

{

pf[j]=cs.pop();

j++;

}

cs.push(isym);

}

}

}

while(!cs.isempty())

{

pf[j]=cs.pop();

j++;

}

}

void display1()

{

for(int i=0;i<pf.length-1;i++)

System.out.print(pf[i]);

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 42

}

public static void main(String args[])throws Exception

{

iftopf ob=new iftopf();

Scanner r=new Scanner(System.in);

System.out.println("enter any equation:");

String s=r.nextLine();

ob.infixtop(s);

ob.display1();

}

}

Output:

6. Write a JAVA/C++ programs to implement the deque (double ended queue) ADT using

DLL and an array.

import java .io.*;

class Dq

{

Dq front,next,prev,rear;

int data;

Dq()

{

data=0;

prev=next=null;

}

Dq(int i)

{

data =i;

prev=next=null;

}

boolean isEmpty()

{

if(front==null)

return true;

return false;

}

Dq insertfront(int item)

{

Dq nn=new Dq(item);

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 43

if(!isEmpty())

{

front.prev=nn;

nn.next=front ;

front=nn;

}

else

{

front=rear=nn;

}

return nn;

}

int deletefront()

{

int k=front.data;

front=front.next;

front.prev=null;

return k;

}

Dq insertrear(int item)

{

Dq ptr;

Dq nn=new Dq(item);

if(!isEmpty())

{

for(ptr=front;ptr.next!=null;ptr=ptr.next);

nn.prev=ptr;

ptr.next=nn;

rear=nn;

}

else

{

front=rear=nn;

}

return nn;

}

int deleterear()

{

int k=rear.data;

rear=rear.prev;

rear.next=null;

return k;

}

Dq getfront()

{

return front;

}

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 44

Dq getrear()

{

return rear;

}

void display()

{

Dq ptr;

if(!isEmpty())

{

for(ptr=front;ptr.next!=null;ptr=ptr.next)

System.out.print(ptr.data+"->");

System.out.print(ptr.data);

}

else

System.out.println("list is empty");

}

int size()

{

if(!isEmpty())

{

int c=0;

for(Dq ptr=front;ptr!=null;ptr=ptr.next)

c++;

return c;

}

else

{

System.out.println("list is empty");

return -1;

}

}

public static void main(String saichandra[])throws Exception

{

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

int ch;

Dq d=new Dq();

do

{

System.out.println();

System.out.println("1.insert front");

System.out.println("2.deletefront");

System.out.println("3.insert rear");

System.out.println("4.deleterear");

System.out.println("5.size");

System.out.println("6.isempty");

System.out.println("7.getfront");

System.out.println("8.getrear");

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 45

System.out.println("ENTER UR CHOICE:");

ch=Integer.parseInt(br.readLine());

switch(ch)

{

case 1:System.out.println("enter element");

int n=Integer.parseInt(br.readLine());

d.insertfront(n);

d.display();

break;

case 2:if(!d.isEmpty())

{

int data1=d.deletefront();

System.out.println("front " +data1+ " is deleted");

d.display();

}

else

System.out.println("list is empty");

break;

case 3:System.out.println("enter element");

int n1=Integer.parseInt(br.readLine());

d.insertrear(n1);

d.display();

break;

case 4:if(!d.isEmpty())

{

int data2=d.deleterear();

System.out.println("rear " +data2+ " is deleted");

d.display();

}

else

System.out.println("list is empty");

break;

case 5:int size=d.size();

if(size!=-1)

System.out.println("size of the dequeue is : "+size);

break;

case 6:System.out.println(d.isEmpty());

break;

case 7:if(!d.isEmpty())

{

Dq x1=d.getfront();

System.out.println("front is:"+x1.data);

}

else

System.out.println("list is empty");

break;

case 8:if(!d.isEmpty())

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 46

{

Dq x2=d.getrear();

System.out.println("rear is:"+x2.data);

}

else

System.out.println("list is empty");

break;

}

}while(ch!=0);

}

}

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 47

7. Write a JAVA/C++ programs that use recursive functions to traverse the given binary

tree in

a) Preorder b) inorder and c) postorder

import java.util.*;

class Traversals

{

Traversals rc,lc;

static Traversals root;

int data;

Traversals a[]=new Traversals[100];

int top=-1;

Traversals()

{

data=0;

rc=lc=null;

}

Traversals(int item)

{

data=item;

lc=rc=null;

}

Traversals[] search(int key)

{

Traversals par ,ptr;

Traversals b[]=new Traversals[2];

ptr=root;

par=null;

while(ptr!=null)

{

if(ptr.data==key)

{

b[0]=par;

b[1]=ptr;

return b;

}

else if(ptr.data<key)

{

par=ptr;

ptr=ptr.rc;

}

else

{

par=ptr;

ptr=ptr.lc;

}

}

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 48

b[0]=par;b[1]=ptr;

return b;

}

void insert(int item)

{

Traversals arr[]=new Traversals[2];

Traversals nn=new Traversals(item);

arr=search(item);

if(root!=null)

{

Traversals par=arr[0];

Traversals ptr=arr[1];

if(ptr!=null)

System.out.println("key already existed");

else

{

if(par.data<item)

par.rc=nn;

else

par.lc=nn;

}

}

else

root=nn;

}

void push(Traversals item)

{

a[++top]=item;

}

Traversals pop()

{

return a[top--];

}

void preorder(Traversals root)

{

Traversals ptr=root;

if(ptr!=null)

push(ptr);

while(top!=-1)

{

ptr=pop();

if(ptr!=null)

{

System.out.println(ptr.data);

push(ptr.rc);

push(ptr.lc);

}

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 49

}

}

void inorder(Traversals root)

{

int count=0,count1=0,count2=0;

Traversals ptr;

ptr=root;

while(top!=-1||ptr!=null)

{

if(ptr!=null).

{

push(ptr);

ptr=ptr.lc;

}

else

{

ptr=pop();

int k=counting(ptr);

if(k==0)count++;

else if(k==1)count1++;

else if(k==2)count2++;

System.out.println(ptr.data);

ptr=ptr.rc;

}

}

System.out.println("2 child nodes:"+count2);

System.out.println("1 child nodes:"+count1);

System.out.println("leaf nodes:"+count);

}

void postorder(Traversals root)

{

Traversals ptr=root;

int f1[]=new int[20];

int i=-1,flag;

do

{

while(ptr!=null)

{

push(ptr);

i++;

f1[i]=0;

if(ptr.rc!=null)

{

push(ptr.rc);

i++;

f1[i]=1;

}

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 50

ptr=ptr.lc;

}

flag=f1[i];

i--;

ptr=pop();

while(flag==0)

{

System.out.println(ptr.data);

ptr=pop();

flag=f1[i];

i--;

}

if(flag==1)

flag=0;

}while(true);

}

int counting(Traversals ptr){

if(ptr.lc!=null&&ptr.rc!=null){return 2;}

else if(ptr.lc!=null||ptr.rc!=null){return 1;}

else return 0;

}

public static void main(String st[])

{

Traversals b=new Traversals();

Scanner s=new Scanner (System.in);

int ch;

do

{

System.out.println("1.insert");

System.out.println("3.search");

System.out.println("4.preorder");

System.out.println("5.inorder");

System.out.println("6.postorder\n7.counting");

System.out.print("enter ur choice:");

ch=s.nextInt();

switch(ch)

{

case 1:System.out.print("enter element:");

int n=s.nextInt();

b.insert(n);

break;

case 3:if(root!=null)

{

System.out.println("enter search element");

int key=s.nextInt();

Traversals search1[]=new Traversals[2];

search1=b.search(key);

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 51

if(search1[1]!=null)

System.out.println("key is found");

else

System.out.println("key not found");

if(search1[0]!=null)

{

if(search1[1]!=null)

System.out.println("parent of the searched element is:"+search1[0].data);

}

else

System.out.println("key is root no parent exist");

}

else

System.out.println("no elements in tree");

break;

case 4:if(root!=null)

b.preorder(root);

else

System.out.println("no elements in tree");

break;

case 5:if(root!=null)

b.inorder(root);

else

System.out.println("no elements in tree");

break;

case 6:if(root!=null)

b.postorder(root);

else

System.out.println("no elements in tree");

break;

case 7:

break;

}

}while(ch!=0);

}

}

Output:

Insert:

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 52

Traversals:

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 53

8. Write a JAVA/C++ programs that use non-recursive functions to traverse the given

binary tree in

a) Preorder b) inorder and c) post order.

import java.util.*;

class Bstnode

{

Bstnode rc,lc;

Bstnode root;

int data;

Bstnode()

{

data=0;

rc=lc=null;

}

Bstnode(int item)

{

data=item;

lc=rc=null;

}

Bstnode[] search(int key)

{

Bstnode par ,ptr;

Bstnode b[]=new Bstnode[2];

ptr=root;

par=null;

while(ptr!=null)

{

if(ptr.data==key)

{

b[0]=par;

b[1]=ptr;

return b;

}

else if(ptr.data<key)

{

par=ptr;

ptr=ptr.rc;

}

else

{

par=ptr;

ptr=ptr.lc;

}

}

b[0]=par;b[1]=ptr;

return b;

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 54

}

void insert(int item)

{

Bstnode arr[]=new Bstnode[2];

Bstnode nn=new Bstnode(item);

arr=search(item);

if(root!=null)

{

Bstnode par=arr[0];

Bstnode ptr=arr[1];

if(ptr!=null)

System.out.println("key already existed");

else

{

if(par.data<item)

par.rc=nn;

else

par.lc=nn;

}

}

else

root=nn;

}

void inorder(Bstnode ptr)

{

if(ptr!=null)

{

inorder(ptr.lc);

System.out.println(ptr.data);

inorder(ptr.rc);

}

}

void preorder(Bstnode ptr)

{

if(ptr!=null)

{

System.out.println(ptr.data);

inorder(ptr.lc);

inorder(ptr.rc);

}

}

void postorder(Bstnode ptr)

{

if(ptr!=null)

{

inorder(ptr.lc);

inorder(ptr.rc);

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 55

System.out.println(ptr.data);

}

}

int deleteleaf(Bstnode par,Bstnode ptr)

{

if(par!=null)

{

if(par.lc==ptr)

par.lc=null;

else

par.rc=null;

}

else

root=null;

return ptr.data;

}

int delete1childnode(Bstnode par,Bstnode ptr)

{

if(par!=null)

{

if(par.lc==ptr)

{

if(ptr.lc==null)

par.lc=ptr.rc;

else

par.lc=ptr.lc;

}

else if(par.rc==ptr)

{

if(ptr.lc==null)

par.rc=ptr.rc;

else

par.rc=ptr.lc;

}

}

else

{

if(ptr.rc!=null)

root=ptr.rc;

else

root=ptr.lc;

}

return ptr.data;

}

int delete2childnode(Bstnode par,Bstnode ptr)

{

Bstnode ptr1=ptr.rc;

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 56

Bstnode par1=null;

while(ptr1.lc!=null)

{

par1=ptr1;

ptr1=ptr1.lc;

}

if(par1!=null)

{

if(ptr1.rc!=null)

par1.lc=ptr1.rc;

else

par1.lc=null;

ptr1.lc=ptr.lc;

ptr1.rc=ptr.rc;

}

else // if par1=null

ptr1.lc = ptr.lc;

if(par!=null)

{

if(par.lc==ptr)

par.lc=ptr1;

else

par.rc=ptr1;

}

else

root=ptr1;

return ptr.data;

}

int deletenode(int item)

{

Bstnode ptr=root,par=null;

boolean flag=false;

int k;

while(ptr!=null&&flag==false)

{

if(item<ptr.data)

{

par=ptr;

ptr=ptr.lc;

}

else if(item>ptr.data)

{

par=ptr;

ptr=ptr.rc;

}

else

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 57

{

ptr.data=item;

flag=true;

}

}

if(flag==false)

{

System.out.println("item not found hence can not delete");

return -1;

}

if(ptr.lc==null&&ptr.rc==null)

k=deleteleaf(par,ptr);

else if(ptr.lc!=null&&ptr.rc!=null)

k=delete2childnode(par,ptr);

else

k=delete1childnode(par,ptr);

return k;

}

public static void main(String saichandra[])

{

Bstnode b=new Bstnode();

Scanner s=new Scanner (System.in);

int ch;

do

{

System.out.println("1.insert");

System.out.println("2.delete");

System.out.println("3.search");

System.out.println("4.inorder");

System.out.println("5.preorder");

System.out.println("6.postorder");

System.out.print("enter ur choice:");

ch=s.nextInt();

switch(ch)

{

case 1:System.out.print("enter element:");

int n=s.nextInt();

b.insert(n);

break;

case 2:if(b.root!=null)

{

System.out.print("enter element:");

int n1=s.nextInt();

int res=b.deletenode(n1);

if(res!=-1)

System.out.println("deleted element is:"+res);

}

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 58

else

System.out.println("no elements in tree");

break;

case 3:if(b.root!=null)

{

System.out.println("enter search element");

int key=s.nextInt();

Bstnode search1[]=new Bstnode[2];

search1=b.search(key);

if(search1[1]!=null)

System.out.println("key is found");

else

System.out.println("key not found");

if(search1[0]!=null)

{

if(search1[1]!=null)

System.out.println("parent of the searched element is:"+search1[0].data);

}

else

System.out.println("key is root no parent exist");

}

else

System.out.println("no elements in tree");

break;

case 4:if(b.root!=null)

b.inorder(b.root);

else

System.out.println("no elements in tree");

break;

case 5:if(b.root!=null)

b.preorder(b.root);

else

System.out.println("no elements in tree");

break;

case 6:if(b.root!=null)

b.postorder(b.root);

else

System.out.println("no elements in tree");

break;

}

}while(ch!=0);

}

}

Output:

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 59

9. Write a JAVA/C++ program to perform the following operations:

a) Insert an element into a BST

b) Delete an element from a BST

c) Search for a key element in a BST

import java.util.*;

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 60

class Bstnode {

Bstnode rc,lc;

Bstnode root;

int data;

Bstnode() {

data=0;

rc=lc=null; }

Bstnode(int item) {

data=item;

lc=rc=null; }

Bstnode[] search(int key) {

Bstnode par ,ptr;

Bstnode b[]=new Bstnode[2];

ptr=root;

par=null;

while(ptr!=null) {

if(ptr.data==key) {

b[0]=par;

b[1]=ptr;

return b; }

else if(ptr.data<key) {

par=ptr;

ptr=ptr.rc; }

else {

par=ptr;

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 61

ptr=ptr.lc; }

}

b[0]=par;b[1]=ptr;

return b; }

void insert(int item) {

Bstnode arr[]=new Bstnode[2];

Bstnode nn=new Bstnode(item);

arr=search(item);

if(root!=null) {

Bstnode par=arr[0];

Bstnode ptr=arr[1];

if(ptr!=null)

System.out.println("key already existed");

else {

if(par.data<item)

par.rc=nn;

else

par.lc=nn; } }

else

root=nn; }

void inorder(Bstnode ptr) {

if(ptr!=null) {

inorder(ptr.lc);

System.out.println(ptr.data);

inorder(ptr.rc); } }

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 62

void preorder(Bstnode ptr) {

if(ptr!=null) {

System.out.println(ptr.data);

inorder(ptr.lc);

inorder(ptr.rc); } }

void postorder(Bstnode ptr) {

if(ptr!=null) {

inorder(ptr.lc);

inorder(ptr.rc);

System.out.println(ptr.data); } }

int deleteleaf(Bstnode par,Bstnode ptr) {

if(par!=null) {

if(par.lc==ptr)

par.lc=null;

else

par.rc=null; }

else

root=null;

return ptr.data; }

int delete1childnode(Bstnode par,Bstnode ptr) {

if(par!=null) {

if(par.lc==ptr) {

if(ptr.lc==null)

par.lc=ptr.rc;

else

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 63

par.lc=ptr.lc; }

else if(par.rc==ptr) {

if(ptr.lc==null)

par.rc=ptr.rc;

else

par.rc=ptr.lc; } }

else {

if(ptr.rc!=null)

root=ptr.rc;

else

root=ptr.lc; }

return ptr.data; }

int delete2childnode(Bstnode par,Bstnode ptr) {

Bstnode ptr1=ptr.rc;

Bstnode par1=null;

while(ptr1.lc!=null) {

par1=ptr1;

ptr1=ptr1.lc; }

if(par1!=null) {

if(ptr1.rc!=null)

par1.lc=ptr1.rc;

else

par1.lc=null;

ptr1.lc=ptr.lc;

ptr1.rc=ptr.rc; }

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 64

else // if par1=null

ptr1.lc = ptr.lc;

if(par!=null) {

if(par.lc==ptr)

par.lc=ptr1;

else

par.rc=ptr1; }

else

root=ptr1;

return ptr.data; }

int deletenode(int item) {

Bstnode ptr=root,par=null;

boolean flag=false;

int k;

while(ptr!=null&&flag==false) {

if(item<ptr.data) {

par=ptr;

ptr=ptr.lc; }

else if(item>ptr.data) {

par=ptr;

ptr=ptr.rc; }

else {

ptr.data=item;

flag=true; } }

if(flag==false) {

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 65

System.out.println("item not found hence can not delete");

return -1; }

if(ptr.lc==null&&ptr.rc==null)

k=deleteleaf(par,ptr);

else if(ptr.lc!=null&&ptr.rc!=null)

k=delete2childnode(par,ptr);

else

k=delete1childnode(par,ptr);

return k; }

public static void main(String saichandra[]) {

Bstnode b=new Bstnode();

Scanner s=new Scanner (System.in);

int ch;

do {

System.out.println("1.insert");

System.out.println("2.delete");

System.out.println("3.search");

System.out.println("4.inorder");

System.out.println("5.preorder");

System.out.println("6.postorder");

System.out.print("enter ur choice:");

ch=s.nextInt();

switch(ch) {

case 1:System.out.print("enter element:");

int n=s.nextInt();

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 66

b.insert(n);

break;

case 2:if(b.root!=null) {

System.out.print("enter element:");

int n1=s.nextInt();

int res=b.deletenode(n1);

if(res!=-1)

System.out.println("deleted element is:"+res); }

else

System.out.println("no elements in tree");

break;

case 3:if(b.root!=null) {

System.out.println("enter search element");

int key=s.nextInt();

Bstnode search1[]=new Bstnode[2];

search1=b.search(key);

if(search1[1]!=null)

System.out.println("key is found");

else

System.out.println("key not found");

if(search1[0]!=null) {

if(search1[1]!=null)

System.out.println("parent of the searched element is:"+search1[0].data);

}

else

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 67

System.out.println("key is root no parent exist");

}

else

System.out.println("no elements in tree");

break;

case 4:if(b.root!=null)

b.inorder(b.root);

else

System.out.println("no elements in tree");

break;

case 5:if(b.root!=null)

b.preorder(b.root);

else

System.out.println("no elements in tree");

break;

case 6:if(b.root!=null)

b.postorder(b.root);

else

System.out.println("no elements in tree");

break; } }

while(ch!=0); } }

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 68

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 69

10.Write JAVA/C++ programs to Implement BFS and DFS of a given graph.

import java.io.*;

import java.util.*;

class queue {

int front,rear;

String que[];

int max,count=0;

queue(int n) {

max=n;

que=new String[max];

front=rear=-1; }

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 70

boolean isfull() {

if(rear==(max-1))

return true;

else

return false; }

boolean isempty() {

if(front==-1)

return true;

else

return false; }

void insert(String n) {

if(isfull())

System.out.println("list is full");

Else {

rear++;

que[rear]=n;

if(front==-1)

front=0;

count++; } }

String delete() {

String x;

if(isempty())

return null;

else {

x=que[front];

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 71

que[front]=null;

if(front==rear)

front=rear=-1;

else

front++;

count--; }

return x; } }

class Graph1 {

String ver[]=new String[20];

static int nverts;

static int size;

int a[][];

Graph1() {

int max=50;

a=new int[max][max];

for(int i=0;i<max;i++)

for(int j=0;j<max;j++)

a[i][j]=0; }

void addVertex(String s) {

int x=search(s);

if(x==-1){

ver[nverts++]=s;

size=nverts;}

else

System.out.println("sorry........................vertex already existed"); }

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 72

void addEdge(String v,String w) {

int i,j;

i=index(v);

j=index(w);

if((i<size)&&(j<size)) {

a[i][j]=1;

a[j][i]=1; }

else

System.out.println("invalid edges"); }

void displayAdj() {

int i,j;

displayVertex();

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

System.out.print(ver[i]+" ");

for(j=0;j<size;j++)

System.out.print(a[i][j]+" ");

System.out.println(); } }

int index(String v) {

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

if(ver[i].equals(v))

return i; }

return a.length; }

void displayEdges() {

int i,j;

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

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 73

for(j=0;j<size;j++)

if(a[i][j]==1)

System.out.println(ver[i]+"->"+ver[j]); } }

void displayVertex() {

for(int i=0;i<size;i++)

System.out.print(" "+ver[i]);

System.out.println(); }

int search(String s) {

int i;

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

if(ver[i].equals(s))

return i; }

return -1; }

String deleteVertex(int n) {

String ss=ver[n];

if(n<size) {

for(int i=n;i<=size;i++) {

for(int j=n;j<=size;j++)

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

ver[i]=ver[i+1]; }

for(int j=n;j<=size;j++) {

for(int i=n;i<=size;i++)

a[i][j]=a[i+1][j];}

size--;

nverts--;

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 74

return ss; }

Else {

size--;

nverts--;

return ss; } }

void removeEdge(String v,String w) {

int i,j;

i=index(v);

j=index(w);

if((i<size)&&(j<size)) {

a[i][j]=0;

a[j][i]=0; }

else

System.out.println("invalid edges"); }

void BFS(String v) {

queue q=new queue(10);

int mark[]=new int[size];

for(int i=0;i<size;i++)

mark[i]=0;

int k=index(v);

mark[k]=1;

q.insert(v);

while(!q.isempty()) {

String s=q.delete();

System.out.println(s);

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 75

int i=index(s);

for(int j=0;j<size;j++) {

if(a[i][j]!=0&&mark[j]!=1) {

mark[j]=1;

q.insert(ver[j]); } } } }

void DFS(String v) {

stack s=new stack(size);

int mark1[]=new int[size];

for(int i=0;i<size;i++)

mark1[i]=0;

int i=index(v);

System.out.println(ver[i]);

s.push(v);

mark1[i]=1;

while(!s.isempty()) {

for(int j=0;j<size;j++) {

int id=index(s.peek());

if(a[id][j]!=0&&mark1[j]!=1) {

s.push(ver[j]);

mark1[j]=1;

System.out.println(ver[j]);

j=-1; } }

s.pop() ; } } }

class stack {

int top,size;

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 76

String ele,s[];

stack(int n) {

s=new String[n];

top=-1; }

void push(String x) {

ele=x;

s[++top]=ele; }

void pop() {

if(!isempty())

top--; }

boolean isempty() {

if(top==-1)

return true;

else

return false; }

String peek() {

return s[top]; } }

class Graph {

public static void main (String str[]) {

Graph1 g=new Graph1();

Scanner sm=new Scanner(System.in);

int ch;

do {

System.out.println();

System.out.println("1.AddVertex");

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 77

System.out.println("2.removeVertex");

System.out.println("3.AddEdge");

System.out.println("4.removeEdge");

System.out.println("5.DisplayAdjacentMatrix");

System.out.println("6.DisplayEdges");

System.out.println("7.BFS");

System.out.println("8.DFS");

System.out.println("0.exit()");

System.out.println("enter ur choice");

ch=sm.nextInt();

switch(ch) {

case 1:System.out.println("enter vertex");

String s1=sm.next();

g.addVertex(s1);

break;

case 2:System.out.println("enter vertex");

String find=sm.next();

int k=g.search(find);

if(k!=-1) {

System.out.println("at:"+k);

System.out.println("deleted:"+g.deleteVertex(k)); }

else

System.out.println("vertex not found try again......................! ");

break;

case 3:System.out.println("enter 2 vertices for creating edge");

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 78

String s2=sm.next();

String s3=sm.next();

g.addEdge(s2,s3);

break;

case 4:System.out.println("enter 2 vertices for deleteing edge");

String s4=sm.next();

String s5=sm.next();

g.removeEdge(s4,s5);

break;

case 5:g.displayAdj();

break;

case 6:g.displayEdges();

break;

case 7: System.out.println("enter vertex");

String s=sm.next();

g.BFS(s);

break;

case 8: System.out.println("enter vertex");

String sm1=sm.next();

g.DFS(sm1);

break; } }

while(ch!=0); } }

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 79

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 80

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 81

11.Write JAVA/C++ programs to Implementing Linear and Binary Search

methods.

import java.io.*;

class LinearSearch

{

public static void main(String a[])throws Exception

{

int arr[]=new int[20];

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.println("nter n value");

int n=Integer.parseInt(br.readLine());

System.out.println("nter elements");

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

{

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 82

arr[i]=Integer.parseInt(br.readLine());

}

System.out.println("nter element to search");

int k=Integer.parseInt(br.readLine());

int cnt=0;

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

{

if(arr[i]==k)

{

System.out.println("element found&position is"+( i+1));

}

else

cnt++;

}

if(cnt==n)

System.out.println("search failed");

}

}

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 83

class Binary

{

private int[] a;

private int n;

public Binary(int max)

{

a=new int[max];

n=0;

}

public int size()

{

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 84

return n;

}

public int find(int k)

{

return recFind(k,0,n-1);

}

private int recFind(int k,int lb,int ub)

{

int curIn;

curIn=(lb+ub)/2;

if(a[curIn]==k)

return curIn;

else if(lb>ub)

return n;

else

{

if(a[curIn]<k)

return recFind(k,curIn+1,ub);

else

return recFind(k,lb,curIn-1);

}

}

public void insert(int val)

{

int j;

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 85

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

if(a[j]>val)

break;

for(int k=n;k>j;k--)

a[k]=a[k-1];

a[j]=val;

n++;

}

public void display()

{

for(int j=0;j<n;j++)

System.out.print(a[j]+" ");

System.out.print("\n");

}

}

class RecBinarySearch

{

public static void main(String arr[])

{

int m=100;

Binary b=new Binary(m);

b.insert(45);

b.insert(90);

b.insert(150);

b.insert(200);

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 86

b.insert(50);

b.display();

int sk=200;

if(b.find(sk)!=b.size())

System.out.println("found"+sk);

else

System.out.println("can't find"+sk);

}

}

12. Write JAVA/C++ programs to implement the following Sorting methods

a) Bubble Sort b) Selection Sort c) Insertion Sort

d) Merge Sort e) Quick Sort f) Heap Sort.

import java.io.*;

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 87

class SortingMethods

{

void bubbleSort(int[] a)

{

int i, pass, exch, n = a.length;

int tmp;

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

{ exch = 0;

for( i = 0; i < n-pass-1; i++ )

if( ((Comparable)a[i]).compareTo(a[i+1]) > 0)

{ tmp = a[i];

a[i] = a[i+1];

a[i+1] = tmp;

exch++;

}

if( exch == 0 ) return;

}

}

void selectionSort( int a[] )

{

int n = a.length;

for( int pass = 0; pass < n-1; pass++ )

{

int min = pass;

for( int i = pass+1; i < n; i++ )

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 88

if( a[i] < a[min] ) min = i;

if( min != pass )

{

int tmp = a[min];

a[min] = a[pass];

a[pass] = tmp;

}

}

}

void display( int a[] )

{

for( int i = 0; i < a.length; i++ )

System.out.print( a[i] + " " );

}

void insertionSort(int a[]) {

int i, j, n = a.length;

int item;

for( j = 1; j < n; j++ ) {

item = a[j];

i = j-1;

while( i >= 0 && ((Comparable)item).compareTo(a[i]) < 0) {

a[i+1] = a[i];

i = i-1; }

a[i+1] = item; } }

void quickSort(int a[], int left, int right) {

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 89

int newleft = left, newright = right;

int amid, tmp;

amid = a[(left + right)/2];

do {

while( (a[newleft] < amid) && (newleft < right))

newleft++;

while( (amid < a[newright]) && (newright > left))

newright--;

if(newleft <= newright) {

tmp = a[newleft];

a[newleft] = a[newright];

a[newright] = tmp;

newleft++; newright--;

}

} while(newleft <= newright);

if(left < newright) quickSort(a, left, newright);

if(newleft < right) quickSort(a, newleft, right);

}

void radixSort(int[] arr, int radix, int maxDigits) {

int d, j, k, m, divisor;

java.util.LinkedList[] queue

= new java.util.LinkedList[radix];

for( d = 0; d < radix; d++ )

queue[d] = new java.util.LinkedList();

divisor = 1;

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 90

for(d = 1; d <= maxDigits; d++) {

for(j = 0; j < arr.length; j++) {

m = (arr[j]/divisor) % radix;

queue[m].addLast(new Integer(arr[j])); }

divisor = divisor*radix;

for(j = k = 0; j < radix; j++) {

while( !queue[j].isEmpty())

arr[k++] = (Integer)queue[j].removeFirst();

} } } }

class MergeSort {

int[] a;

int[] tmp;

MergeSort(int[] arr) {

a = arr;

tmp = new int[a.length]; }

void msort() {

sort(0, a.length-1); }

void sort(int left, int right) {

if(left < right) {

int mid = (left+right)/2;

sort(left, mid);

sort(mid+1, right);

merge(left, mid, right); } }

void merge(int left, int mid, int right) {

int i = left;

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 91

int j = left;

int k = mid+1;

while( j <= mid && k <= right ) {

if(a[j] < a[k])

tmp[i++] = a[j++];

else

tmp[i++] = a[k++]; }

while( j <= mid )

tmp[i++] = a[j++];

for(i=left; i < k; i++)

a[i] = tmp[i]; } }

class Heap {

int[] a;

int maxSize;

int currentSize;

public Heap(int m) {

maxSize = m;

currentSize = 0;

a = new int[maxSize]; }

public boolean insert(int key) {

if(currentSize == maxSize)

return false;

a[currentSize] = key;

moveUp(currentSize++);

return true; }

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 92

public void moveUp(int index) {

int parent = (index-1)/2;

int bottom = a[index];

while(index > 0 && a[parent] < bottom) {

a[index] = a[parent];

index = parent;

parent = (parent-1)/2; }

a[index] = bottom; }

public int remove() {

if( isEmpty() )

{ System.out.println("Heap is empty");

return -1; }

int root = a[0];

a[0] = a[--currentSize];

moveDown(0);

return root; }

public void moveDown(int index) {

int largerChild;

int top = a[index];

while(index < currentSize/2) {

int leftChild = 2*index+1;

int rightChild = 2*index+2;

if(rightChild<currentSize && a[leftChild]<a[rightChild] )

largerChild = rightChild;

else

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 93

largerChild = leftChild;

if(top >= a[largerChild]) break;

a[index] = a[largerChild];

index = largerChild; }

a[index] = top; }

public boolean isEmpty()

{ return currentSize==0; }

void heapsort(int []arr) {

Heap h = new Heap(arr.length);

for(int i = 0; i < arr.length; i++)

h.insert(arr[i]);

for( int i = arr.length-1; i >= 0; i-- )

arr[i] = h.remove(); } }

class AllSorts {

public static void main(String[] args) throws IOException

{ int[] arr = {75, 40, 10, 90, 50, 95, 55, 15, 65};

int n;

do {

System.out.println("\n1-Bubblesort\n2-Selection sort\n3-Insertion sort\n4-Quicksort\n5-Merge sort\n6-

Heapsort\n7-Radix sort\n0-exit");

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter ur choice of sort:");

n=Integer.parseInt(br.readLine());

SortingMethods obj= new SortingMethods();

System.out.print("\n Unsorted array: ");

obj.display( arr );

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 94

switch(n) {

case 1: obj.bubbleSort(arr);

break;

case 2: obj.selectionSort( arr );

break;

case 3: obj.insertionSort(arr);

break;

case 4: obj.quickSort( arr, 0, arr.length-1 );

break;

case 5: MergeSort ms=new MergeSort(arr);

ms.msort();

break;

case 6: Heap hs=new Heap(9);

hs.heapsort(arr);

break;

case 7: obj.radixSort(arr,9,4);

break; }

System.out.print("\n Sorted array: ");

obj.display( arr );

}while(n!=0); } }

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 95

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 96

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 97

14. Write a JAVA/C++ program to insert and delete an element from an AVL-tree.

import java.io.*;

import java.util.*;

class Avlnode {

int ele;

Avlnode left;

Avlnode right;

int height;

static Avlnode root;

Avlnode() {

ele=0;

left=right=null; }

Avlnode(int d) {

ele=d;

left=right=null; }

Avlnode insert(int x,Avl node t) {

if(t==null) {

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 98

t=new Avlnode(x);

if(t==null)

System.out.println("out of space!!!");

Else {

t.ele=x;

t.height=0;

t.left=null;t.right=null; } }

else if(x<t.ele) {

t.left=insert(x,t.left);

if(height(t.left)-height(t.right)==2)

if(x<t.left.ele)

t=SingleRotateWithLeft(t);

else

t=DoubleRotateWithLeft(t); }

else if(x>t.ele) {

t.right=insert(x,t.right);

if((height(t.right)-height(t.left))==2)

if(x>t.right.ele)

t=SingleRotateWithRight(t);

else

t=DoubleRotateWithRight(t); }

t.height=max(height(t.left),height(t.right))+1;

return t; }

static Avlnode SingleRotateWithLeft(Avlnode k2) {

Avlnode k1;

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 99

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

static Avlnode DoubleRotateWithLeft(Avlnode k3) {

k3.left=SingleRotateWithRight(k3.left);

return SingleRotateWithLeft(k3); }

static Avlnode SingleRotateWithRight(Avlnode k2) {

Avlnode k1;

k1=k2.right;

k2.right=k1.left;

k1.left=k2;

k2.height=max(height(k2.left),height(k2.right))+1;

k1.height=max(height(k1.right),k2.height)+1;

return k1; }

static Avlnode DoubleRotateWithRight(Avlnode k3) {

k3.right=SingleRotateWithLeft(k3.right);

return SingleRotateWithRight(k3); }

static int max(int a,int b) {

if(a>b)

return a;

else

return b; }

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 100

static int height(Avlnode p) {

if(p==null)

return -1;

else

return p.height; }

void preorder(Avlnode sms) {

if(sms!=null)

{preorder(sms.left);

System.out.print(sms.ele+" ");

preorder(sms.right); } } }

class Avltree{

public static void main(String sms[])throws Exception {

Avlnode an=new Avlnode();

Scanner s=new Scanner(System.in);

int ch;

Avlnode root=null;

Do {

System.out.println("1.insert");

System.out.println("2.traversal");

System.out.println("0.exit");

System.out.println("enter ur choice");

ch=s.nextInt();

switch(ch) {

case 1:

System.out.println("enter element");

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 101

int n=s.nextInt();

root=an.insert(n,root);

break;

case 2:an.preorder(root);

break; }

}while(ch!=0); }

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 102

15. Write a JAVA/C++ program to implement all the functions of a dictionary

(ADT) using hashing.

import java.util.*;

import java.io.*;

class Hash1 {

int item,size;

int hArray[];

static int cnt;

Hash1(int n) {

size=n;

hArray=new int[size];

for(int i=0;i<size;i++)

hArray[i]=-99; }

int Hashfun(int key) {

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 103

key=key%7;

return key; }

void insert(int key) {

if(cnt>=size)

System.out.println("insertion failed as array full....................!");

else {

int hvalue=Hashfun(key);int j=1;

while(hArray[hvalue]!=-99) {

hvalue=hvalue+(j*j); //Quadratic probing

hvalue=hvalue%size;

j++; }

hArray[hvalue]=key;

cnt++; } }

int search(int key) {

int searchval=Hashfun(key);int j=1;

while(hArray[searchval]!=-99) {

if(hArray[searchval]==key)

return searchval;

searchval=searchval+(j*j);

searchval=searchval%size;

j++; }

return -1; }

int delete(int key) {

int delkey=search(key);

if(delkey==-1) {

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 104

System.out.println("deletion failed as key not found");

return -1; }

Else {

hArray[delkey]=-99;

return key; } }

void display() {

for(int j=0;j<size;j++) {

System.out.println(j+": "+hArray[j]+"\n"); }

} }

class HashdemoQ {

public static void main(String saichandra[])throws Exception

{

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.println("enter array size:");

int size=Integer.parseInt(br.readLine());

int ch;

Hash1 h=new Hash1(size);

Do {

System.out.println("1.insert\n2.display\n3.search\n4.delete");

System.out.println("enter choice:");

ch=Integer.parseInt(br.readLine());

switch(ch) {

case 1:int n=Integer.parseInt(br.readLine());

h.insert(n);break;

case 2:

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 105

h.display();break;

case 3: int find=Integer.parseInt(br.readLine());

int r= h.search(find);

if(r!=-1)

System.out.println("element is found at:"+r+" index");

else

System.out.println("element is not found");

break;

case 4: int key=Integer.parseInt(br.readLine());

int dr= h.delete(key);

if(dr!=-1)

System.out.println(dr+" is deleted");

h.display();

break; }

}while(ch!=0); } }

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 106

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 107

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 108

Additional programs:

Write JAVA/C++ programs to implement the List ADT using Arrays

import java.io.*;

interface ListADT

{

void traversal();

boolean isFull();

boolean isEmpty();

int search(int key);

void insertAtBeg(int item);

void insertAtEnd(int item);

void insertAtPos(int pos,int item);

void insertAfterPos(int pos,int item);

void insertAfterKey(int key,int item);

void delete(int key);

void deletePos(int pos);

}

class ArrayDS implements ListADT

{

int a[],n,max;

ArrayDS(int cap)

{

max=cap;

a=new int[max];

n=0;

}

public void traversal()

{

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

System.out.print(a[i]+" ");

System.out.println("\n");

}

public boolean isFull()

{

if(n==max)

return true;

return false;

}

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 109

public boolean isEmpty()

{

if(n==0)

return true;

return false;

}

public int search(int key)

{

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

if(a[i]==key)

return i;

return -1;

}

public void insertAtBeg(int item)

{

if(!isFull())

{

for(int i=n-1;i>=0;i--)

a[i+1]=a[i];

a[0]=item;

n++;

}

else

System.out.println("Array is Full, cannot insert");

}

public void insertAtEnd(int item)

{

if(!isFull())

{

a[n++]=item;

}

else

System.out.println("Array is Full, cannot insert");

}

public void insertAtPos(int pos,int item)

{

if(!isFull())

{

for(int i=n-1;i>=pos;i--)

a[i+1]=a[i];

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 110

a[pos]=item;

n++;

}

else

System.out.println("Cannot insert, Array is Full");

}

public void insertAfterPos(int pos,int item)

{

if(pos<n)

insertAtPos(pos+1,item);

else

System.out.println("Array is Full, cannot insert");

}

public void insertAfterKey(int key,int item)

{

int p=search(key);

if(p==-1)

System.out.println("Cannot insert");

else

insertAfterPos(p,item);

}

public void delete(int key)

{

if(!isEmpty())

{

int p=search(key);

deletePos(p);

}

else

System.out.println("Array is Empty");

}

public void deletePos(int pos)

{

if(!isEmpty())

{

if(pos<0||pos>n-1)

{

System.out.println("Cannot delete, Element not found");

}

else

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 111

{

for(int i=pos;i<n-1;i++)

a[i]=a[i+1];

n--;

}

}

else

System.out.println("Array is Empty");

}

}

class ArrayTest

{

public static void main(String arg[]) throws IOException

{

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter the size of the Array");

int n=Integer.parseInt(br.readLine());

ArrayDS ar=new ArrayDS(n);

System.out.println("Array is created");

ar.traversal();

int t,k,m=1;

do

{

System.out.println("Enter ur choice of operation");

System.out.println("1-insertAtBeg\n2-insertAtEnd\n3-insertAtPos\n4-

insertAfterPos\n5-insertAfterKey\n6-deleteItem\n7-deletePos\n0-exit");

n=Integer.parseInt(br.readLine());

switch(n)

{

case 1:

System.out.println("Enter the element to be inserted");

t=Integer.parseInt(br.readLine());

ar.insertAtBeg(t);

ar.traversal();

break;

case 2:

System.out.println("Enter the element to be inserted");

t=Integer.parseInt(br.readLine());

ar.insertAtEnd(t);

ar.traversal();

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 112

break;

case 3:

System.out.println("Enter the element to be inserted:");

t=Integer.parseInt(br.readLine());

System.out.println("Enter the index position to insert at:");

k=Integer.parseInt(br.readLine());

ar.insertAtPos(k,t);

ar.traversal();

break;

case 4:

System.out.println("Enter the element to be inserted");

t=Integer.parseInt(br.readLine());

System.out.println("Enter the index position to insert after");

k=Integer.parseInt(br.readLine());

ar.insertAfterPos(k,t);

ar.traversal();

break;

case 5:

System.out.println("Enter the element to be inserted:");

t=Integer.parseInt(br.readLine());

System.out.println("Enter the key element to insert aftter:");

k=Integer.parseInt(br.readLine());

ar.insertAfterKey(k,t);

ar.traversal();

break;

case 6:

System.out.println("Enter the element to be deleted");

t=Integer.parseInt(br.readLine());

ar.delete(t);

ar.traversal();

break;

case 7:

System.out.println("Enter the position to be deleted");

t=Integer.parseInt(br.readLine());

ar.deletePos(t);

ar.traversal();

break;

case 0:

m=0;

break;

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 113

default:

System.out.println("INVALID CHOICE");

}

}while(m==1);

ar.traversal();

}

}

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 114

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 115

Write a JAVA program to check the paranthesis(),{},<> are closed properly or not

in a given string

import java.io.*;

class Node

{

char data;

Node next;

Node()

{

this(' ');

}

Node(char data)

{

this.data=data;

next=null;

}

Node(char data,Node next)

{

this.data=data;

this.next=next;

}

}

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 116

class StackLLImp

{

Node top;

void traversal()

{

Node ptr;

ptr=top;

while(ptr!=null)

{

System.out.println(ptr.data);

ptr=ptr.next;

}

System.out.println();

}

boolean isEmpty()

{

if(top==null)

return true;

return false;

}

char peek()

{

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 117

if(top!=null)

return top.data;

return '#';

}

void push(char item)

{

Node nn=new Node(item,top);

top=nn;

}

char pop()

{

if(top!=null)

{

char k=top.data;

top=top.next;

return k;

}

else

System.out.println("Stack is Empty");

return '#';

}

int size()

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 118

{

int cnt=0;

Node ptr=top;

while(ptr!=null)

{

cnt++;

ptr=ptr.next;

}

return cnt;

}}

class Parenthesis

{

static boolean isPair(char ch,char ch2)

{

if(ch=='('&&ch2==')')

return true;

if(ch=='{'&&ch2=='}')

return true;

if(ch=='<'&&ch2=='>')

return true;

return false;

}

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 119

public static void main(String ar[]) throws IOException

{

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

StackLLImp st=new StackLLImp();

System.out.println("Enter the string to check");

String str=br.readLine();

int flag=0;

char ch,ch2;

for(int i=0;i<str.length();i++)

{

ch=str.charAt(i);

if(ch=='('||ch=='{'||ch=='<')

st.push(ch);

else

if(ch==')'||ch=='}'||ch=='>')

{

ch2=st.pop();

if(!isPair(ch2,ch))

{

System.out.println("\nThe paranthesis "+ch2+" is not closed properly");

flag=1;

}

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 120

}}

if(!st.isEmpty())

System.out.println("\nThe paranthesis "+st.pop()+" is not closed properly");

else

if(flag==0)

System.out.println("\nAll the paranthesis are placed properly");

}

}

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 121

Program to check whether a string is palindrome or not.(Using both Stack and

Queue

import java.io.*;

class Node

{

char data;

Node next;

Node()

{

this(' ');

}

Node(char data)

{

this.data=data;

next=null;

}

Node(char data,Node next)

{

this.data=data;

this.next=next;

}

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 122

}

class StackLL

{

Node top;

boolean isEmpty()

{

if(top==null)

return true;

return false;

}

void push(char item)

{

Node nn=new Node(item,top);

top=nn;

}

char pop()

{

if(top!=null)

{

char k=top.data;

top=top.next;

return k;

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 123

}

else

System.out.println("Stack is Empty");

return '#';

}

}

class Que

{

Node front,rear;

boolean isEmpty()

{

if(front==null)

return true;

return false;

}

void enqueue(char item)

{

Node nn=new Node(item);

if(isEmpty())

front=rear=nn;

else

{

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 124

rear.next=nn;

rear=nn;

}

}

char delqueue()

{

char k=' ';

if(isEmpty())

System.out.println("Cannot delete,Queue is empty");

else

if(front==rear)

{

k=front.data;

front=rear=null;

}

else

{

k=front.data;

front=front.next;

}

return k;

}

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 125

}

class PalinTest

{

public static void main(String ar[]) throws IOException

{

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

StackLL st=new StackLL();

Que q=new Que();

System.out.println("Enter any string to check whether PALINDROME OR NOT");

String str=br.readLine();

int i,flag=0,l=str.length();

char ch1,ch2;

for(i=0;i<l/2;i++)

st.push(str.charAt(i));

i=(l+1)/2;

while(i<l)

{

q.enqueue(str.charAt(i));

i++;

}

for(i=0;i<l/2;i++)

if(st.pop()!=q.delqueue())

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 126

{

flag=1;

break;

}

if(flag==0)

System.out.println("\n"+str+" is a PALINDROME");

else

System.out.println("\n"+str+" is NOT A PALINDROME");

}}

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 127

Write a JAVA Program to implement PriorityQueue

class Node

{ String data;

int prn;

Node next;

Node( String str, int p )

{ data = str;

prn = p;

}

}

class LinkedPriorityQueue

{

Node head;

public void insert(String item, int pkey)

{

Node newNode = new Node(item, pkey);

int k;

if( head == null ) k = 1;

else if( newNode.prn < head.prn ) k = 2;

else k = 3;

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 128

switch( k )

{ case 1: head = newNode;

head.next = null;

break;

case 2: Node oldHead = head;

head = newNode;

newNode.next = oldHead;

break;

case 3: Node p = head;

Node prev = p;

Node nodeBefore = null;

while( p != null )

{

if( newNode.prn < p.prn )

{ nodeBefore = p;

break;

}

else

{ prev = p;

p = p.next;

}

}

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 129

newNode.next = nodeBefore;

prev.next = newNode;

}

}

public Node delete()

{

if( isEmpty() )

{ System.out.println("Queue is empty");

return null;

}

else

{ Node tmp = head;

head = head.next;

return tmp;

}

}

public void displayList()

{

Node p = head;

System.out.print("\nQueue: ");

while( p != null )

{

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 130

System.out.print(p.data+"(" +p.prn+ ")" + " ");

p = p.next;

}

System.out.println();

}

public boolean isEmpty()

{ return (head == null); }

public Node peek()

{ return head; }

}

class LinkedPriorityQueueDemo

{

public static void main(String[] args)

{

LinkedPriorityQueue pq = new LinkedPriorityQueue();

Node item;

pq.insert("kumar", 3);

pq.insert("anil", 2);

pq.insert("Kishor", 2);

pq.insert("Ravi", 1);

pq.insert("Siva", 3);

pq.displayList();

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 131

item = pq.delete();

if( item != null )

System.out.println("delete():" + item.data

+ "(" +item.prn+")");

pq.displayList();

pq.insert("Arnold", 2);

pq.insert("Neeru", 1);

pq.insert("Hasini", 4);

pq.displayList();

}

}

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 132

Write a JAVA/C++ program that illustrate prefix evaluation

import java.util.*;

import java.lang.*;

class intstack

{

int top,size;

int stack[],num;

intstack(int n)

{

size=n;

top=-1;

stack=new int[n];

}

int peek()

{

return stack[top];

}

void push(int x)

{

if(!isfull())

{

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 133

stack[++top]=x;

}

else

System.out.println("operation failed as stack is full");

}

int pop()

{

if(!isempty())

{

return stack[top--];

}

{

System.out.println("operation failed as stack is empty");

return -1;

}

}

boolean isempty()

{

if(top==-1)

return true;

return false;

}

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 134

boolean isfull()

{

if(top>size)

return true;

return false;

}

}

class pfeeval

{

intstack is;

pfeeval()

{

is=new intstack(20);

}

boolean isoperator(char op)

{

if(op=='+'||op=='-'||op=='*'||op=='/'||op=='('||op==')'||op=='^')

return true;

return false;

}

int pfeevaluation(String pf)

{

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 135

int res=0;

char ch[]=pf.toCharArray();

for(int i=0;i<ch.length;i++)

{

if(!isoperator(ch[i]))

{

String s=Character.toString(ch[i]);

int k=Integer.parseInt(s);

is.push(k);

}

else if(ch[i]!='('||ch[i]!=')')

{

int p1=is.pop();

int p2=is.pop();

if(ch[i]=='+')

res=p2+p1;

else if(ch[i]=='-')

res=p2-p1;

else if(ch[i]=='/')

res=p2/p1;

else if(ch[i]=='*')

res=p2*p1;

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 136

else if(ch[i]=='^')

res=p2^p1;

is.push(res);

}

}

return(is.pop());

}

public static void main(String str[])

{

pfeeval ob=new pfeeval();

Scanner s=new Scanner(System.in);

String r=s.nextLine();

int res1=ob.pfeevaluation(r);

System.out.println(res1);

}

}

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 137

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 138

Write JAVA/C++ programs to implement the circular queue ADT using an

array.

import java.util.*;

class CirQue

{

int front,rear,next=0;

int que[];

int max,count=0;

CirQue(int n)

{

max=n;

que=new int[max];

front=rear=-1;

}

boolean isfull()

{

if(front==(rear+1)%max)

return true;

else

return false;

}

boolean isempty()

{

if(front==-1&&rear==-1)

return true;

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 139

else

return false;

}

int delete()

{

if(isempty())

{

return -1;

}

else

{

count --;

int x=que[front];

if(front==rear)

front=rear=-1;

else

{

next=(front+1)%max;

front=next;

}

return x;

}

}

void insert(int item)

{

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 140

if(isempty())

{

que[++rear]=item;

front=rear;

count ++;

}

else if(!isfull())

{

next=(rear+1)%max;

if(next!=front)

{

que[next]=item;

rear=next;

}

count ++;

}

else

System.out.println("q is full");

}

void display()

{

if(isempty())

System.out.println("queue is empty");

else

next=(front)%max;

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 141

while(next<=rear)

{

System.out.println(que[next]);

next++;

}

}

int size()

{

return count;

}

public static void main(String args[])

{

int ch;

Scanner s=new Scanner(System.in);

System.out.println("enter limit");

int n=s.nextInt();

CirQue q=new CirQue(n);

do

{

System.out.println("1.insert");

System.out.println("2.delete");

System.out.println("3.display");

System.out.println("4.size");

System.out.println("enter ur choice :");

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 142

ch=s.nextInt();

switch(ch)

{

case 1:System.out.println("enter element :");

int n1=s.nextInt();

q.insert(n1);

break;

case 2:int c1=q.delete();

if(c1>0)

System.out.println("deleted element is :"+c1);

else

System.out.println("can't delete");

break;

case 3:q.display();

break;

case 4:System.out.println("queue size is "+q.size());

break;

}

}

while(ch!=0);

}

}

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 143

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 144

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 145

Write a JAVA Program to traverse Binary Tree using LEVEL order traversal

class Node

{

Object data;

Node left;

Node right;

Node( Object d )

{ data = d; }

}

class BinaryTree

{ Object tree[];

int maxSize;

java.util.LinkedList<Node> que =

new java.util.LinkedList<Node>();

BinaryTree( Object a[], int n )

{ maxSize = n;

tree = new Object[maxSize];

for( int i=0; i<maxSize; i++ )

tree[i] = a[i];

}

public Node buildTree( int index )

{ Node p = null;

if( tree[index] != null )

{ p = new Node(tree[index]);

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 146

p.left = buildTree(2*index+1);

p.right = buildTree(2*index+2);

}

return p;

}

public void levelorder(Node p)

{

que.addLast(p);

while( !que.isEmpty() )

{

p = que.removeFirst();

System.out.print(p.data + " ");

if(p.left != null)

que.addLast(p.left);

if(p.right != null)

que.addLast(p.right);

}

}

}

class LevelOrderTraversal

{

public static void main(String args[])

{

Object arr[] = {'E', 'C', 'G', 'A', 'D', 'F', 'H',

null,'B', null, null, null, null,

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 147

null, null, null, null, null, null};

BinaryTree t = new BinaryTree( arr, arr.length );

Node root = t.buildTree(0);

System.out.print("\n Level Order Tree Traversal: ");

t.levelorder(root);

}

}

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 148

Write a JAVA Program to create BinarySearchTree and to count Leaf nodes

class BSTNode

{

int data;

BSTNode left;

BSTNode right;

BSTNode( int d )

{ data = d; }

}

class BinarySearchTree

{

public BSTNode insertTree(BSTNode p, int key)

{

if( p == null )

p = new BSTNode(key);

else if( key < p.data)

p.left = insertTree( p.left, key);

else p.right = insertTree( p.right, key);

return p;

}

int leafNodes(BSTNode p)

{

int count = 0;

if( p != null)

{ if((p.left == null) && (p.right == null))

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 149

count = 1;

else

count = count + leafNodes(p.left)

+ leafNodes(p.right);

}

return count;

}

public void inorder(BSTNode p)

{ if( p != null )

{ inorder(p.left);

System.out.print(p.data + " ");

inorder(p.right);

}

}

}

class BinarySearchTreeDemo

{ public static void main(String args[])

{

int arr[] = { 45, 25, 15, 10, 20, 30, 65, 55, 50, 60, 75, 80 };

BinarySearchTree bst = new BinarySearchTree();

BSTNode root = null;

for( int i = 0; i < arr.length; i++ )

root = bst.insertTree( root, arr[i]);

BSTNode root2 = root;

System.out.print("\n Number of leaf nodes: " + bst.leafNodes(root));

GRIET MCA DEPT.

DATA STRUCTURES LAB MCA II SEMESTER Page 150

System.out.print("\n Inorder: ");

bst.inorder(root);

int key = 44;

bst.insertTree(root, key);

System.out.print("\n Inorder, after insertion of " + key + ": ");

bst.inorder(root);

} }