0% found this document useful (0 votes)
5 views61 pages

Data Structures Using Java Lab

The document is a laboratory manual for a Data Structures using Java course at Swarnandhra Institute of Engineering and Technology. It includes various experiments and Java program implementations for data structures such as searching algorithms, lists, stacks, queues, trees, and graphs. The manual serves as a guide for students to complete their lab work and document their findings.
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)
5 views61 pages

Data Structures Using Java Lab

The document is a laboratory manual for a Data Structures using Java course at Swarnandhra Institute of Engineering and Technology. It includes various experiments and Java program implementations for data structures such as searching algorithms, lists, stacks, queues, trees, and graphs. The manual serves as a guide for students to complete their lab work and document their findings.
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/ 61

lOMoARcPSD|22118788

DATA Structures Using JAVA LAB

Electronics and communication engineering (Jawaharlal Nehru Technological University,


Kakinada)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by 8005 Swarnalatha ([email protected])
lOMoARcPSD|22118788

DATA STRUCTURES USING JAVA LAB

Laboratory Manual

Enrollment No:

Name:

Year & Semester: III Year & I Semester

Swarnandhra Institute of Engineering and Technology

Department of Electronics and Communication


2022-23

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

Swarnandhra Institute of Engineering and Technology


Seetarampuram, Narsapuram.

Certificate

Swarnandhra Institute of Engineering and Technology


Department of Electronics and Communication
2022-23

This is to certify that the Lab/term work carried out in the subject of

DATA STRUCTURES USING JAVA LAB and recorded in this journal is the

bonafide work of Mr./Miss .........................................................................


Enrollment No....................................of III B.Tech. Isemester in the branch of

……………………………………….. during the academic year 2022- 2023.

Faculty In charge Head of the Department


Date: Date:

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

INDEX
S.NO DATE EXPERIMENT NAME SIGN REMARKS
1. Write Java programs that use both recursive and non-
recursive functions for implementing
the following searching methods:
(a) Linear search (b) Binary search
2. Write Java programs to implement the following using arrays
and linked lists List ADT
a) List using Arrays
b) List Using LinkedList
3. Write Java programs to implement the following using an
array.
(a) Stack ADT (b) Queue ADT
4. Write a java program that reads an infix expression, converts
the expression to postfix form
and then evaluates the postfix expression (use stack ADT).
5. Write Java programs to implement the following using a
singly linked list.
(a) Stack ADT (b) Queue ADT
6. Write Java programs to implement the deque (double ended
queue) ADT using
(a) Array
(b) Doubly linked list.
7. Write a Java program to implement a priority queue ADT

8. Write Java programs that use recursive and non-recursive


functions to traverse the given binarytree in
a)Preorder
b) Inorder
c) Postorder
9. write a java program that dispalys node values in a level
order traversal (traverse the tree one level at a
time,starting at the root node) for a binary tree
10. write a java program that uses recursive functions
to create a binary search tree

11. write a java program for implementation of bfs and dfs for a
given graph
12. write a java program for implementing the following sorting
methods:

a)Bubble sort

b)Selection sort

c)Insertion sort
13. write a java program for implementing kmp pattern matching
algorithm

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

ADVANCED DATA STRUCTURES AND ALGORITHMS LAB

1. Write Java programs that use both recursive and non-recursive functions
for implementing
the following searching methods:
(a) Linear search (b) Binary search

1(a) Linear Search using non-recursive function

import java.io.*;
class LinearSearch
{
public static void main(String args[]) throws IOException
{
int count=0;
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("enter n value");
int n=Integer.parseInt(br.readLine());
int arr[]=new int[n];
System.out.println("enter elements");
for(int i=0;i<n;i++)
{
arr[i]=Integer.parseInt(br.readLine());
}
System.out.println("enter element to search");
int key=Integer.parseInt(br.readLine());
for(int i=0;i<n;i++)
{
if(arr[i]==key)
System.out.println("element found : " + key + " in position :" + (i+1));
else
count++;
}
if(count==n)
System.out.println(key + " element not found, search failed");
}
}

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

OUTPUT:

//Linear Search using recursive function

import java.io.*;
class RecursiveLinearSearch
{
public static int arr[], key;
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("enter n value");
int n=Integer.parseInt(br.readLine());
arr=new int[n];
System.out.println("enter elements");
for(int i=0;i<n;i++)
{
arr[i]=Integer.parseInt(br.readLine());
}
System.out.println("enter element to search");
key=Integer.parseInt(br.readLine());
if( linearSearch(arr.length-1) )
System.out.println(key + " found in the list" );
else
System.out.println(key + " not found in the list");
}
static boolean linearSearch(int n)
{
if( n < 0 ) return false;
if(key == arr[n])
return true;
else
return linearSearch(n-1);
}
}

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

OUTPUT:

1 (b) Binary Search using non-recursive function


class BinarySearch
{
static Object[] a = { "AP", "KA", "MH", "MP", "OR", "TN", "UP", "WB"};
static Object key = "UP";
public static void main(String args[])
{
if( binarySearch() )
System.out.println(key + " found in the list");
else
System.out.println(key + " not found in the list");
}
static boolean binarySearch()
{
int c, mid, low = 0, high = a.length-1;
while( low <= high)
{
mid = (low + high)/2;
c = ((Comparable)key).compareTo(a[mid]);
if( c < 0) high = mid-1;
else if( c > 0) low = mid+1;
else return true;
}
return false;
}
}

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

OUTPUT:

import java.io.*;
class RecursiveBinarySearch
{
public static int arr[], key;
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter n value");
int n=Integer.parseInt(br.readLine());
arr=new int[n];
System.out.println("enter elements");
for(int i=0;i<n;i++)
{
arr[i]=Integer.parseInt(br.readLine());
}
System.out.println("enter element to search");
key=Integer.parseInt(br.readLine());
if( binarySearch(0, arr.length-1) )
System.out.println(key + " found in the list");
else
System.out.println(key + " not found in the list");
}
static boolean binarySearch(int low, int high)
{
if( low > high ) return false;
int mid = (low + high)/2;
int c = ((Comparable)key).compareTo(arr[mid]);
if( c < 0) return binarySearch(low, mid-1);
else if( c > 0) return binarySearch(mid+1, high);

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

else return true;


}
}
OUTPUT:

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

2. Write Java programs to implement the following using arrays and linked lists List ADT
a) List using Arrays
//List.java
public interface List
{
public void createList(int n);
public void insertFirst(Object ob);
public void insertAfter(Object ob, Object pos);
public Object deleteFirst();
public Object deleteAfter(Object pos);
public boolean isEmpty();
public int size();
}
// ArrayList.java
class ArrayList implements List
{
class Node
{
Object data;
int next;
Node(Object ob, int i) // constructor
{
data = ob;
next = i;
}
}
int MAXSIZE; // max number of nodes in the list
Node list[]; // create list array
int head, count; // count: current number of nodes in the list
ArrayList( int s) // constructor
{
MAXSIZE = s;
list = new Node[MAXSIZE];
}
public void initializeList()
{
for( int p = 0; p < MAXSIZE-1; p++ )
list[p] = new Node(null, p+1);
list[MAXSIZE-1] = new Node(null, -1);
}
public void createList(int n) // create ‘n’ nodes
{
int p;
for( p = 0; p < n; p++ )
{
list[p] = new Node(11+11*p, p+1);
count++;
}
list[p-1].next = -1; // end of the list

}
public void insertFirst(Object item)
{

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

if( count == MAXSIZE )


{
System.out.println("***List is FULL");
return;
}
int p = getNode();
if( p != -1 )
{
list[p].data = item;
if( isEmpty() ) list[p].next = -1;
else list[p].next = head;
head = p;
count++;
}
}
public void insertAfter(Object item, Object x)
{
if( count == MAXSIZE )
{
System.out.println("***List is FULL");
return;
}
int q = getNode(); // get the available position to insert new node
int p = find(x); // get the index (position) of the Object x
if( q != -1 )
{
list[q].data = item;
list[q].next = list[p].next;
list[p].next = q;
count++;
}
}
public int getNode() // returns available node index
{
for( int p = 0; p < MAXSIZE; p++ )
if(list[p].data == null)
return p;
return -1;
}
public int find(Object ob) // find the index (position) of the Object ob
{
int p = head;
while( p != -1)
{
if( list[p].data == ob ) return p;
p = list[p].next; // advance to next node
}
return -1;
}
public Object deleteFirst()
{
if( isEmpty() )
{

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

System.out.println("List is empty: no deletion");


return null;
}
Object tmp = list[head].data;
if( list[head].next == -1 ) // if the list contains one node,
head = -1; // make list empty.
else
head = list[head].next;
count--; // update count
return tmp;
}
public Object deleteAfter(Object x)
{
int p = find(x);
if( p == -1 || list[p].next == -1 )
{
System.out.println("No deletion");
return null;
}
int q = list[p].next;
Object tmp = list[q].data;
list[p].next = list[q].next;
count--;
return tmp;
}
public void display()
{
int p = head;
System.out.print("\nList: [ " );
while( p != -1)
{
System.out.print(list[p].data + " "); // print data
p = list[p].next; // advance to next node
}
System.out.println("]\n");//
}
public boolean isEmpty()
{
if(count == 0) return true;
else return false;
}
public int size()
{
return count;
}
}
// ArrayListDemo.java
class ArrayListDemo

public static void main(String[] args)


{

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

ArrayList linkedList = new ArrayList(10);


linkedList.initializeList();
linkedList.createList(4); // create 4 nodes
linkedList.display(); // print the list
System.out.print("InsertFirst 55:");
linkedList.insertFirst(55);
linkedList.display();
System.out.print("Insert 66 after 33:");
linkedList.insertAfter(66, 33); // insert 66 after 33
linkedList.display();
Object item = linkedList.deleteFirst();
System.out.println("Deleted node: " + item);
linkedList.display();
System.out.print("InsertFirst 77:");
linkedList.insertFirst(77);
linkedList.display();
item = linkedList.deleteAfter(22); // delete node after node 22
System.out.println("Deleted node: " + item);
linkedList.display();
System.out.println("size(): " + linkedList.size());
}
}

OUTPUT:

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

b) List Using LinkedList


//LinkedListDemo.java
class LinkedList implements List
{
class Node
{
Object data; // data item
Node next; // refers to next node in the list
Node( Object d ) // constructor
{
data = d;
} // ‘next’ is automatically set to null
}
Node head; // head refers to first node
Node p; // p refers to current node
int count; // current number of nodes
public void insertFirst(Object item) // insert at the beginning of list
{
p = new Node(item); // create new node
p.next = head; // new node refers to old head
head = p; // new head refers to new node
count++;
}
public void insertAfter(Object item,Object key)
{
p = find(key); // get “location of key item”

if( p == null )
System.out.println(key + " key is not found");
else
{
Node q = new Node(item); // create new node
q.next = p.next; // new node next refers to p.next
p.next = q; // p.next refers to new node
count++;
}
}
public Node find(Object key)
{
p = head;
while( p != null ) // start at beginning of list until end of list
{
if( p.data == key ) return p; // if found, return key address
p = p.next; // move to next node
}
return null; // if key search is unsuccessful, return null
}
public Object deleteFirst() // delete first node
{

if( isEmpty() )
{
System.out.println("List is empty: no deletion");

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

return null;
}
Node tmp = head; // tmp saves reference to head
head = tmp.next;
count--;
return tmp.data;
}
public Object deleteAfter(Object key) // delete node after key item
{
p = find(key); // p = “location of key node”
if( p == null )
{
System.out.println(key + " key is not found");
return null;
}
if( p.next == null ) // if(there is no node after key node)
{
System.out.println("No deletion");
return null;
}
else
{
Node tmp = p.next; // save node after key node
p.next = tmp.next; // point to next of node deleted
count--;
return tmp.data; // return deleted node

}
}
public void displayList()
{
p = head; // assign mem. address of 'head' to 'p'
System.out.print("\nLinked List: ");
while( p != null ) // start at beginning of list until end of list
{
System.out.print(p.data + " -> "); // print data
p = p.next; // move to next node
}
System.out.println(p); // prints 'null'
}
public boolean isEmpty() // true if list is empty
{
return (head == null);
}
public int size()
{
return count;
}
} // end of LinkeList class

class LinkedListDemo
{
public static void main(String[] args)

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

{
LinkedList list = new LinkedList(); // create list object
list.createList(4); // create 4 nodes
list.displayList();
list.insertFirst(55); // insert 55 as first node
list.displayList();
list.insertAfter(66, 33); // insert 66 after 33
list.displayList();
Object item = list.deleteFirst(); // delete first node
if( item != null )
{
System.out.println("deleteFirst(): " + item);
list.displayList();
}
item = list.deleteAfter(22); // delete a node after node(22)
if( item != null )
{
System.out.println("deleteAfter(22): " + item);
list.displayList();
}
System.out.println("size(): " + list.size());

}
}
OUTPUT:

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

3. Write Java programs to implement the following using an array.


(a) Stack ADT (b) Queue ADT
3(a) stack ADT using array
import java.io.*;
class stackclass
{
int top,ele,stack[],size;
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())

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

return stack[top];
else
{
System.out.println("stack is empty");
return -1;
}
}
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())

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

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

ele=Integer.parseInt(br.readLine());
s.push(ele);
}
else
{
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;
case 8 :System.exit(1);

}
}while(ch!=0);
}
}

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

OUTPUT:

3(b)Queue ADT using array


import java.util.*;
class queue
{
int front,rear;
int que[];
int max,count=0;
queue(int n)

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

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

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()
{

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

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

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

OUTPUT:

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

4. Write a java program that reads an infix expression, converts the expression to postfix form
and then evaluates the postfix expression (use stack ADT).
import java.io.*;
class InfixToPostfix
{
java.util.Stack<Character> stk =new java.util.Stack<Character>();
public String toPostfix(String infix)
{
infix = "(" + infix + ")"; // enclose infix expr within parentheses
String postfix = "";
/* scan the infix char-by-char until end of string is reached */
for( int i=0; i<infix.length(); i++)
{
char ch, item;
ch = infix.charAt(i);
if( isOperand(ch) ) // if(ch is an operand), then
postfix = postfix + ch; // append ch to postfix string
if( ch == '(' ) // if(ch is a left-bracket), then
stk.push(ch); // push onto the stack
if( isOperator(ch) ) // if(ch is an operator), then
{
item = stk.pop(); // pop an item from the stack
/* if(item is an operator), then check the precedence of ch and item*/

if( isOperator(item) )
{
if( precedence(item) >= precedence(ch) )
{
stk.push(item);
stk.push(ch);
}
else
{
postfix = postfix + item;
stk.push(ch);
}
}
else
{
stk.push(item);
stk.push(ch);
}
} // end of if(isOperator(ch))
if( ch == ')' )
{
item = stk.pop();
while( item != '(' )
{

postfix = postfix + item;


item = stk.pop();
}
}

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

} // end of for-loop
return postfix;
} // end of toPostfix() method
public boolean isOperand(char c)
{
return(c >= 'A' && c <= 'Z');
}
public boolean isOperator(char c)
{
return( c=='+' || c=='-' || c=='*' || c=='/' );
}
public int precedence(char c)
{
int rank = 1; // rank = 1 for '*’ or '/'
if( c == '+' || c == '-' ) rank = 2;
return rank;
}
}

//InfixToPostfixDemo.java
class InfixToPostfixDemo
{
public static void main(String args[]) throws IOException
{
InfixToPostfix obj = new InfixToPostfix();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Expression:");
String infix = br.readLine();
//String infix = "A*(B+C/D)-E";
System.out.println("infix: " + infix );
System.out.println("postfix:"+obj.toPostfix(infix) );
}
}

OUTPUT:

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

5. Write Java programs to implement the following using a singly linked list.

(a) Stack ADT (b) Queue ADT


//5 (a) Stack
import java.io.*;
class Stack1
{
Stack1 top,next,prev;
int data;
Stack1()
{
data=0;
next=prev=null;
}
Stack1(int d)
{
data=d;
next=prev=null;
}
void push(int n)
{
Stack1 nn;
nn=new Stack1(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()

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

if(top==null)
return true;
else
return false;
}
void display()
{
Stack1 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));
Stack1 a=new Stack1();
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();
}

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

else
{

System.out.println("list is empty");
}
}
}while(ch!=0);
}
}
OUTPUT:

5 (b). Queue
import java.io.*;
class Qlnk
{
Qlnk front,rear,next;
int data;
Qlnk()
{
data=0;
next=null;

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

}
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()
{
if(rear==null)
return true;

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

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

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

}
}while(ch!=0);
}
}

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

6. Write Java programs to implement the deque (double ended queue) ADT using
(a) Array
(b) Doubly linked list.
(a): An ArrayDeque Class
public class ArrayDeque {
private int maxSize;
private Object[] que;
private int first;
private int last;
private int count; // current number of items in deque
public ArrayDeque(int s) { // constructor
maxSize = s;
que = new Object[maxSize];
first = last = -1;
count = 0;
}
public void addLast(Object item) {
if(count == maxSize) {
System.out.println("Deque is full"); return;
}
last = (last+1) % maxSize;
que[last] = item;
if(first == -1 && last == 0) first = 0;
count++;
}
public Object removeLast() {
if(count == 0) {
System.out.println("Deque is empty"); return(' ');
}
Object item = que[last];
que[last] = „ ‟;
if(last > 0)
last = (last-1) % maxSize;
count--;
if(count == 0)
first = last = -1;
return(item);
}
public void addFirst(Object item){
if(count == maxSize){
System.out.println("Deque is full"); return;
}
if(first > 0)
first = (first-1) % maxSize;
else if(first == 0)
first = maxSize-1;
que[first] = item;
count++;
}

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

public Object removeFirst() {


if(count == 0) {
System.out.println("Deque is empty");
return(' ');
}
Object item = que[first];
que[first] = „ ‟;
if(first == maxSize-1)
first = 0;
else
first = (first+1) % maxSize;
count--;
if(count == 0)
first = last = -1;
return(item);
}
void display() {
System.out.println("----------------------------");
System.out.print("first:"+first + ", last:"+ last);
System.out.println(", count: " + count);
System.out.println(" 0 1 2 3 4 5");
System.out.print("Deque: ");
for( int i=0; i<maxSize; i++ )
System.out.print(que[i]+ " ");
System.out.println("\n----------------------------");
}
public boolean isEmpty(){ // true if queue is empty
return (count == 0);
}
public boolean isFull(){ // true if queue is full
return (count == maxSize);
}
}
class ArrayDequeDemo {
public static void main(String[] args) {
ArrayDeque q = new ArrayDeque(6); // queue holds a max of 6 items
q.insertLast('A'); /* (a) */
q.insertLast('B');
q.insertLast('C');
q.insertLast('D');
System.out.println("deleteFirst():"+q.deleteFirst());
q.display();
q.insertLast('E'); /* (b) */
q.display(); /* (c) */
System.out.println("deleteLast():"+q.deleteLast());
System.out.println("deleteLast():"+q.deleteLast());
q.display();
q.insertFirst('P'); q.insertFirst('Q'); /* (d) */
q.insertFirst('R'); q.display();

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

q.deleteFirst(); q.display(); /* (e) */


q.insertFirst('X'); q.display(); /* (f) */
q.insertLast('Y'); q.display(); /* (g) */
q.insertLast('Z'); q.display(); /* (h) */
}
}
Output:
deleteFirst(): A
----------------------------
first:1, last:3, count: 3
0 1 2 3 4 5
Deque: B C D
----------------------------
first:1, last:4, count: 4
0 1 2 3 4 5
Deque: B C D E
----------------------------
deleteLast(): E
deleteLast(): D
----------------------------
first:1, last:2, count: 2
0 1 2 3 4 5
Deque: B C
----------------------------
first:4, last:2, count: 5
0 1 2 3 4 5
Deque: P B C R Q
----------------------------
first:5, last:2, count: 4
0 1 2 3 4 5
Deque: P B C Q
----------------------------
first:4, last:2, count: 5
0 1 2 3 4 5
Deque: P B C X Q
----------------------------
first:4, last:3, count: 6
0 1 2 3 4 5
Deque: P B C Y X Q
----------------------------
Deque is full
----------------------------
first:4, last:3, count: 6
0 1 2 3 4 5
Deque: P B C Y X Q

(b): A LinkedDeque class


public class LinkedDeque {
public class DequeNode {
DequeNode prev;
Object data;
DequeNode next;
DequeNode( Object item ) // constructor
{
data = item;
} // prev & next automatically refer to null

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

}
private DequeNode first, last;
private int count;
public void addFirst(Object item){
if( isEmpty() )
first = last = new DequeNode(item);
else {
DequeNode tmp = new DequeNode(item);
tmp.next = first;
first.prev = tmp;
first = tmp;
}
count++;
}
public void addLast(Object item){
if( isEmpty() )
first = last = new DequeNode(item);
else{
DequeNode tmp = new DequeNode(item);
tmp.prev = last;
last.next = tmp;
last = tmp;
}
count++;
}
public Object removeFirst(){
if( isEmpty() ){
System.out.println("Deque is empty");
return null;
}
else {
Object item = first.data;
first = first.next;
first.prev = null;
count--;
return item;
}
}
public Object removeLast() {
if( isEmpty() ){
System.out.println("Deque is empty");
return null;
}
else {
Object item = last.data;
last = last.prev;
last.next = null;
count--;
return item;

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

}
}
public Object getFirst(){
if( !isEmpty() )
return( first.data );
else
return null;
}
public Object getLast(){
if( !isEmpty() )
return( last.data );
else
return null;
}
public boolean isEmpty(){
return (count == 0);
}
public int size(){
return(count);
}
public void display(){
DequeNode p = first;
System.out.print("Deque: [ ");
while( p != null ){
System.out.print( p.data + " " );
p = p.next;
}
System.out.println("]");
}
}
public class LinkedDequeDemo {
public static void main( String args[]){
LinkedDeque dq = new LinkedDeque();
System.out.println("removeFirst():" + dq.removeFirst());
dq.addFirst('A');
dq.addFirst('B');
dq.addFirst('C');
dq.display();
dq.addLast('D');
dq.addLast('E');
System.out.println("getFirst():" + dq.getFirst());
System.out.println("getLast():" + dq.getLast());
dq.display();
System.out.println("removeFirst():"+dq.removeFirst());
System.out.println("removeLast():"+ dq.removeLast());
dq.display();
System.out.println("size():" + dq.size());
}
}

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

Output:
Deque is empty
removeFirst(): null
Deque: [ C B A ]
getFirst(): C
getLast(): E
Deque: [ C B A D E ]
removeFirst(): C
removeLast(): E
Deque: [ B A D ]
size(): 3

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

7. Write a Java program to implement a priority queue ADT.


public class Node {
String data; // data item
int prn; // priority number (minimum has highest priority)
Node next; // "next" refers to the next node
Node( String str, int p ) { // constructor
data = str;
prn = p;
} // "next" is automatically set to null
}
class LinkedPriorityQueue {
Node head; // “head” refers to first node
public void insert(String item, int pkey){ // insert item after pkey
Node newNode = new Node(item, pkey); // create new node
int k;
if( head == null )
k = 1;
else if( newNode.prn < head.prn )
k = 2;
else
k = 3;
switch( k ){
case 1: head = newNode; // Q is empty, add head node
head.next = null;
break;
case 2: Node oldHead = head; // add one item before head
head = newNode;
newNode.next = oldHead;
break;
case 3: Node p = head; // add item before a node
Node prev = p;
Node nodeBefore = null;
while( p != null ) {
if( newNode.prn < p.prn ){
nodeBefore = p; break;
}
else {
prev = p; // save previous node of current node
p = p.next; // move to next node
}
} // end of while
newNode.next = nodeBefore;
prev.next = newNode;
} // end of switch
} // end of insert() method
public Node delete(){
if( isEmpty() ){
System.out.println("Queue is empty");

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

return null;
}
else {
Node tmp = head;
head = head.next;
return tmp;
}
}
public void displayList() {
Node p = head; // assign address of head to p
System.out.print("\nQueue: ");
while( p != null ) // start at beginning of list until end of list
{
System.out.print(p.data+"(" +p.prn+ ")" + " ");
p = p.next; // move to next node
}
System.out.println();
}
public boolean isEmpty() // true if list is empty
{
return (head == null);
}
public Node peek() // get first item
{
return head;
}
class LinkedPriorityQueueDemo {
public static void main(String[] args){
LinkedPriorityQueue pq = new LinkedPriorityQueue();
Node item;
pq.insert("Babu", 3);
pq.insert("Nitin", 2);
pq.insert("Laxmi", 2);
pq.insert("Kim", 1);
pq.insert("Jimmy", 3);
pq.displayList();
item = pq.delete();
if( item != null )
System.out.println("delete():" + item.data + "(" +item.prn+")");
pq.displayList();
pq.insert("Scot", 2);
pq.insert("Anu", 1);
pq.insert("Lehar", 4);
pq.displayList();
} }
Output:
Queue: Kim(1) Nitin(2) Laxmi(2) Babu(3) Jimmy(3)
delete(): Kim(1)
Queue: Nitin(2) Laxmi(2) Babu(3) Jimmy(3)
Queue: Anu(1) Nitin(2) Laxmi(2) Scot(2) Babu(3) Jimmy(3) Lehar(4)

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

8. Write Java programs that use recursive and non-recursive functions to traverse the given
binarytree in
APreorder
b) Inorder
c) Postorder.
class Node
{
Object data;
Node left;
Node right;
Node( Object d ) // constructor
{
data = d;
}}
class BinaryTree
{
Object tree[];
int maxSize;
java.util.Stack<Node> stk = new java.util.Stack<Node>();
BinaryTree( Object a[], int n ) // constructor
{
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]);
p.left = buildTree(2*index+1);
p.right = buildTree(2*index+2);
}
return p;
}
/* Recursive methods - Binary tree traversals */
public void inorder(Node p)
{
if( p != null )
{
inorder(p.left);
System.out.print(p.data + " ");
inorder(p.right);
}}
public void preorder(Node p)
{
if( p != null )
{
System.out.print(p.data + " ");

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

preorder(p.left);
preorder(p.right);
}}
public void postorder(Node p)
{
if( p != null )
{
postorder(p.left);
postorder(p.right);
System.out.print(p.data + " ");
}}
/* Non-recursive methods - Binary tree traversals */
public void preorderIterative(Node p)
{
if(p == null )
{
System.out.println("Tree is empty");
return;
}
stk.push(p);
while( !stk.isEmpty() )
{
p = stk.pop();
if( p != null )
{
System.out.print(p.data + " ");
stk.push(p.right);
stk.push(p.left);
}}}
public void inorderIterative(Node p)
{
if(p == null )
{
System.out.println("Tree is empty");
return;
}
while( !stk.isEmpty() || p != null )
{
if( p != null )
{
stk.push(p); // push left-most path onto stack
p = p.left;
}
else
{
p = stk.pop(); // assign popped node to p
System.out.print(p.data + " "); // print node data
p = p.right; // move p to right subtree
}}}
public void postorderIterative(Node p)
{
if(p == null )
{

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

System.out.println("Tree is empty");
return;
}
Node tmp = p;
while( p != null )
{
while( p.left != null )
{
stk.push(p);
p = p.left;
}
while( p != null && (p.right == null || p.right == tmp ))
{
System.out.print(p.data + " "); // print node data
tmp = p;
if( stk.isEmpty() )
return;
p = stk.pop();
}
stk.push(p);
p = p.right;
} } } // end of BinaryTree class
class BinaryTreeDemo
{
public static void main(String args[])
{
Object arr[] = {'E', 'C', 'G', 'A', 'D', 'F', 'H', null,'B',
null, null, null, null, null, null, null, null, null, null };
BinaryTree t = new BinaryTree( arr, arr.length );
Node root = t.buildTree(0); // buildTree() returns reference to root
System.out.print("\n Recursive Binary Tree Traversals:");
System.out.print("\n inorder: ");
t.inorder(root);
System.out.print("\n preorder: ");
t.preorder(root);
System.out.print("\n postorder: ");
t.postorder(root);
System.out.print("\n Non-recursive Binary Tree Traversals:");
System.out.print("\n inorder: ");
t.inorderIterative(root);
System.out.print("\n preorder: ");
t.preorderIterative(root);
System.out.print("\n postorder: ");
t.postorderIterative(root);
}
}
OUTPUT:

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

9. write a java program that dispalys node values in a level order traversal (traverse
the tree one level at a time,starting at the root node) for a binary tree

1. // A class for creation of nodes of the binary Tree


2. // nodes of the binary tree contain
3. // a left and a right reference
4. // and a value of the node
5. class TreeNode
6. {
7. // for holding value of the node
8. int val;
9.
10. // for referring to the other nodes
11. TreeNode left, right;
12.
13. // constructor of the class TreeNode
14. // the construct initializes the class fields
15. public TreeNode(int i)
16. {
17. val = i;
18. right = left = null;
19. }
20. }
21.
22. public class BTreeLevelOrder
23. {
24. // top node i.e. root of the Binary Tree
25. TreeNode r;
26.
27. // constructor of the class BTree
28. public BTreeLevelOrder() { r = null; }
29.
30. // method for displaying the level order traversal of the binary tree
31. void displayLevelOrder()
32. {
33. int ht = treeHeight(r);
34. int j;
35.
36. for (j = 1; j <= ht; j++)
37. {
38. displayCurrentLevel(r, j);
39. }
40. }
41.
42. // finding the "height" of the binary tree
43. // Note that the total number of nodes
44. // present in the longest path from the topmost node (root node_

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

45. // to the leaf node, which is farthest from the root node, gives the
46. // height of the tree
47. int treeHeight(TreeNode r)
48. {
49. if (r == null)
50. {
51. return 0;
52. }
53. else
54. {
55. // finding the height of the left and right subtrees
56. int lh = treeHeight(r.left);
57. int rh = treeHeight(r.right);
58.
59. // picking up the larger one
60. if (lh > rh)
61. {
62. return (lh + 1);
63. }
64. else
65. {
66. return (rh + 1);
67. }
68. }
69. }
70.
71. // Printing nodes present in the current level
72. void displayCurrentLevel(TreeNode r, int l)
73. {
74. // null means nothing is there to print
75. if (r == null)
76. {
77. return;
78. }
79.
80. // l == 1 means only one node
81. // is present in the binary tree
82. if (l == 1)
83. {
84. System.out.print(r.val + " ");
85. }
86.
87. // l > 1 means either there are nodes present in
88. // the left side of the current node or in the
89. // right side of the current node or in both sides
90. // therefore, we have to look in the left as well as in

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

91. // the right side of the current node


92. else if (l > 1)
93. {
94. displayCurrentLevel(r.left, l - 1);
95. displayCurrentLevel(r.right, l - 1);
96. }
97. }
98.
99. // main method
100. public static void main(String argvs[])
101. {
102. // creating an object of the class BTreeLevelOrder
103. BTreeLevelOrder tree = new BTreeLevelOrder ();
104.
105. // root node
106. tree.r = new TreeNode(18);
107.
108. // remaining nodes of the tree
109. tree.r.left = new TreeNode(20);
110. tree.r.right = new TreeNode(30);
111. tree.r.left.left = new TreeNode(60);
112. tree.r.left.right = new TreeNode(34);
113. tree.r.right.left = new TreeNode(45);
114. tree.r.right.right = new TreeNode(65);
115. tree.r.left.left.left = new TreeNode(12);
116. tree.r.left.left.right = new TreeNode(50);
117. tree.r.left.right.left = new TreeNode(98);
118. tree.r.left.right.right = new TreeNode(82);
119. tree.r.right.left.left = new TreeNode(31);
120. tree.r.right.left.right = new TreeNode(59);
121. tree.r.right.right.left = new TreeNode(71);
122. tree.r.right.right.right = new TreeNode(41);
123.
124.
125. System.out.println("Level order traversal of binary tree is ");
126. tree.displayLevelOrder();
127. }
128. }

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

10. write a java program that uses recursive functions


to create a binary search tree

class BST_class {
//node class that defines BST node
class Node {
int key;
Node left, right;

public Node(int data){


key = data;
left = right = null;
}
}
// BST root node
Node root;

// Constructor for BST =>initial empty tree


BST_class(){
root = null;
}
//delete a node from BST
void deleteKey(int key) {
root = delete_Recursive(root, key);
}

//recursive delete function


Node delete_Recursive(Node root, int key) {
//tree is empty
if (root == null) return root;

//traverse the tree


if (key < root.key) //traverse left subtree
root.left = delete_Recursive(root.left, key);
else if (key > root.key) //traverse right subtree
root.right = delete_Recursive(root.right, key);
else {
// node contains only one child
if (root.left == null)
return root.right;
else if (root.right == null)
return root.left;

// node has two children;


//get inorder successor (min value in the right subtree)
root.key = minValue(root.right);

// Delete the inorder successor


root.right = delete_Recursive(root.right, root.key);
}

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

return root;
}

int minValue(Node root) {


//initially minval = root
int minval = root.key;
//find minval
while (root.left != null) {
minval = root.left.key;
root = root.left;
}
return minval;
}

// insert a node in BST


void insert(int key) {
root = insert_Recursive(root, key);
}

//recursive insert function


Node insert_Recursive(Node root, int key) {
//tree is empty
if (root == null) {
root = new Node(key);
return root;
}
//traverse the tree
if (key < root.key) //insert in the left subtree
root.left = insert_Recursive(root.left, key);
else if (key > root.key) //insert in the right subtree
root.right = insert_Recursive(root.right, key);
// return pointer
return root;
}

// method for inorder traversal of BST


void inorder() {
inorder_Recursive(root);
}

// recursively traverse the BST


void inorder_Recursive(Node root) {
if (root != null) {
inorder_Recursive(root.left);
System.out.print(root.key + " ");
inorder_Recursive(root.right);
}
}

boolean search(int key) {


root = search_Recursive(root, key);
if (root!= null)
return true;
else
return false;

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

//recursive insert function


Node search_Recursive(Node root, int key) {
// Base Cases: root is null or key is present at root
if (root==null || root.key==key)
return root;
// val is greater than root's key
if (root.key > key)
return search_Recursive(root.left, key);
// val is less than root's key
return search_Recursive(root.right, key);
}
}
class Main{
public static void main(String[] args) {
//create a BST object
BST_class bst = new BST_class();
/* BST tree example
45
/ \
10 90
/ \ /
7 12 50 */
//insert data into BST
bst.insert(45);
bst.insert(10);
bst.insert(7);
bst.insert(12);
bst.insert(90);
bst.insert(50);
//print the BST
System.out.println("The BST Created with input data(Left-root-
right):");
bst.inorder();

//delete leaf node


System.out.println("\nThe BST after Delete 12(leaf node):");
bst.deleteKey(12);
bst.inorder();
//delete the node with one child
System.out.println("\nThe BST after Delete 90 (node with 1 child):");
bst.deleteKey(90);
bst.inorder();

//delete node with two children


System.out.println("\nThe BST after Delete 45 (Node with two
children):");
bst.deleteKey(45);
bst.inorder();
//search a key in the BST
boolean ret_val = bst.search (50);
System.out.println("\nKey 50 found in BST:" + ret_val );
ret_val = bst.search (12);
System.out.println("\nKey 12 found in BST:" + ret_val );
} }

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

11. write a java program for implementation of bfs and dfs for a
given graph

Implementing BFS in Java | Breadth First Search Algorithm

BFS Algorithm

The general process of exploring a graph using breadth-first search includes the following steps:-

 Take the input for the adjacency matrix or adjacency list for the graph.
 Initialize a queue.
 Enqueue the root node (in other words, put the root node into the beginning of the queue).
 Dequeue the head (or first element) of the queue, then enqueue all of its neighboring nodes,
starting from left to right. If a node has no neighboring nodes which need to be explored, simply
dequeue the head and continue the process. (Note: If a neighbor which is already explored or in
the queue appears, don’t enqueue it – simply skip it.)
 Keep repeating this process till the queue is empty.

import java.io.*;
import java.util.*;

class Graph
{
private int V; //number of nodes in the
graph
private LinkedList<Integer> adj[]; //adjacency list
private Queue<Integer> queue; //maintaining a queue

Graph(int v)
{
V = v;
adj = new LinkedList[v];
for (int i=0; i<v; i++)
{
adj[i] = new LinkedList<>();
}
queue = new LinkedList<Integer>();
}

void addEdge(int v,int w)


{

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

adj[v].add(w); //adding an edge to the


adjacency list (edges are bidirectional in this example)
}

void BFS(int n)
{

boolean nodes[] = new boolean[V]; //initialize boolean array


for holding the data
int a = 0;

nodes[n]=true;
queue.add(n); //root node is added to the top of
the queue

while (queue.size() != 0)
{
n = queue.poll(); //remove the top element of the
queue
System.out.print(n+" "); //print the top element of the
queue

for (int i = 0; i < adj[n].size(); i++) //iterate through the


linked list and push all neighbors into queue
{
a = adj[n].get(i);
if (!nodes[a]) //only insert nodes into
queue if they have not been explored already
{
nodes[a] = true;
queue.add(a);
}
}
}
}

public static void main(String args[])


{
Graph graph = new Graph(6);

graph.addEdge(0, 1);
graph.addEdge(0, 3);
graph.addEdge(0, 4);
graph.addEdge(4, 5);
graph.addEdge(3, 5);

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

graph.addEdge(1, 2);
graph.addEdge(1, 0);
graph.addEdge(2, 1);
graph.addEdge(4, 1);
graph.addEdge(3, 1);
graph.addEdge(5, 4);
graph.addEdge(5, 3);

System.out.println("The Breadth First Traversal of the graph is as


follows :");

graph.BFS(0);
}
}

Implementing DFS in Java | Depth First Search Algorithm

DFS Algorithm

The general process of exploring a graph using depth first search includes the following steps:-

 Take the input for the adjacency matrix or adjacency list for the graph.
 Initialize a stack.
 Push the root node (in other words, put the root node into the beginning of the stack).
 If the root node has no neighbors, stop here. Else push the leftmost neighboring node which
hasn’t already been explored into the stack. Continue this process till a node is encountered
which has no neighbors (or whose neighbors have all been added to the stack already) – stop
the process then, pop the head, and then continue the process for the node which is popped.
 Keep repeating this process till the stack becomes empty.

import java.io.*;
import java.util.*;

class Graph {
private int V; //number of nodes

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

private LinkedList<Integer> adj[]; //adjacency list

public Graph(int v)
{
V = v;
adj = new LinkedList[v];
for (int i = 0; i < v; ++i)
{
adj[i] = new LinkedList();
}

void addEdge(int v, int w)


{
adj[v].add(w); //adding an edge to the
adjacency list (edges are bidirectional in this example)
}

void DFSUtil(int vertex, boolean nodes[])


{

nodes[vertex] = true; //mark the node as


explored
System.out.print(vertex + " ");
int a = 0;

for (int i = 0; i < adj[vertex].size(); i++) //iterate through the


linked list and then propagate to the next few nodes
{
a = adj[vertex].get(i);
if (!nodes[a]) //only propagate to next
nodes which haven't been explored
{
DFSUtil(a, nodes);
}
}
}

void DFS(int v)
{
boolean already[] = new boolean[V]; //initialize a new
boolean array to store the details of explored nodes
DFSUtil(v, already);
}

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

public static void main(String args[])


{
Graph g = new Graph(6);

g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 0);
g.addEdge(1, 3);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 4);
g.addEdge(3, 5);
g.addEdge(4, 3);
g.addEdge(5, 3);

System.out.println(
"Following is Depth First Traversal: ");

g.DFS(0);
}
}

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

12. write a java program for implementing the following sorting methods:

a)Bubble sort

b)Selection sort

c)Insertion sort

a)Bubble sort

public class BubbleSortExample {

static void bubbleSort(int[] arr) {

int n = arr.length;

int temp = 0;

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

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

if(arr[j-1] > arr[j]){

//swap elements

temp = arr[j-1];

arr[j-1] = arr[j];

arr[j] = temp;

public static void main(String[] args) {

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

int arr[] ={3,60,35,2,45,320,5};

System.out.println("Array Before Bubble Sort");

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

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

System.out.println();

bubbleSort(arr);//sorting array elements using bubble sort

System.out.println("Array After Bubble Sort");

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

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

b)Selection sort

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

1. import java.util.Scanner;
2.
3. public class SelectionSortExample2
4. {
5. public static void main(String args[])
6. {
7. int size, i, j, temp;
8. int arr[] = new int[50];
9. Scanner scan = new Scanner(System.in);
10.
11. System.out.print("Enter Array Size : ");
12. size = scan.nextInt();
13.
14. System.out.print("Enter Array Elements : ");
15. for(i=0; i<size; i++)
16. {
17. arr[i] = scan.nextInt();
18. }
19.
20. System.out.print("Sorting Array using Selection Sort Technique..\n");
21. for(i=0; i<size; i++)
22. {
23. for(j=i+1; j<size; j++)
24. {
25. if(arr[i] > arr[j])
26. {
27. temp = arr[i];
28. arr[i] = arr[j];
29. arr[j] = temp;
30. }
31. }
32. }
33.
34. System.out.print("Now the Array after Sorting is :\n");
35. for(i=0; i<size; i++)
36. {
37. System.out.print(arr[i]+ " ");
38. }
39. }
40. }

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

c)Insertion sort

1. public class InsertionSortExample {


2. public static void insertionSort(int array[]) {
3. int n = array.length;
4. for (int j = 1; j < n; j++) {
5. int key = array[j];
6. int i = j-1;
7. while ( (i > -1) && ( array [i] > key ) ) {
8. array [i+1] = array [i];
9. i--;
10. }
11. array[i+1] = key;
12. }
13. }
14.
15. public static void main(String a[]){
16. int[] arr1 = {9,14,3,2,43,11,58,22};
17. System.out.println("Before Insertion Sort");
18. for(int i:arr1){
19. System.out.print(i+" ");
20. }
21. System.out.println();
22.
23. insertionSort(arr1);//sorting array using insertion sort
24.
25. System.out.println("After Insertion Sort");
26. for(int i:arr1){

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

27. System.out.print(i+" ");


28. }
29. }
30. }

13. write a java program for implementing kmp pattern matching algorithm

// JAVA program for implementation of KMP pattern


// searching algorithm

class KMP_String_Matching {
void KMPSearch(String pat, String txt)
{
int M = pat.length();
int N = txt.length();

// create lps[] that will hold the longest


// prefix suffix values for pattern
int lps[] = new int[M];
int j = 0; // index for pat[]

// Preprocess the pattern (calculate lps[]


// array)
computeLPSArray(pat, M, lps);

int i = 0; // index for txt[]


while (i < N) {
if (pat.charAt(j) == txt.charAt(i)) {
j++;
i++;
}
if (j == M) {
System.out.println("Found pattern "
+ "at index " + (i - j));
j = lps[j - 1];
}

// mismatch after j matches


else if (i < N && pat.charAt(j) != txt.charAt(i)) {
// Do not match lps[0..lps[j-1]] characters,
// they will match anyway

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

if (j != 0)
j = lps[j - 1];
else
i = i + 1;
}
}
}

void computeLPSArray(String pat, int M, int lps[])


{
// length of the previous longest prefix suffix
int len = 0;
int i = 1;
lps[0] = 0; // lps[0] is always 0

// the loop calculates lps[i] for i = 1 to M-1


while (i < M) {
if (pat.charAt(i) == pat.charAt(len)) {
len++;
lps[i] = len;
i++;
}
else // (pat[i] != pat[len])
{
// This is tricky. Consider the example.
// AAACAAAA and i = 7. The idea is similar
// to search step.
if (len != 0) {
len = lps[len - 1];

// Also, note that we do not increment


// i here
}
else // if (len == 0)
{
lps[i] = len;
i++;
}
}
}
}

// Driver program to test above function


public static void main(String args[])
{
String txt = "ABABDABACDABABCABAB";
String pat = "ABABCABAB";
new KMP_String_Matching().KMPSearch(pat, txt);
}
}

Downloaded by 8005 Swarnalatha ([email protected])


lOMoARcPSD|22118788

Downloaded by 8005 Swarnalatha ([email protected])

You might also like