Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 28

Page

DATA STRUCTURES USING JAVA LAB


1. Write a Program to implement the Linked List operations
2. Write a Program to implement the Stack operations using an array.
3. Write Programs to implement the Queue operations using an array.
4. Write Programs to implement the Stack operations using a singly linked list.
5. Write Programs to implement the Queue operations using a singly linked list.
6. Write a program for arithmetic expression evaluation
7. Write a program to implement Double Ended Queue using a doubly linked list.
8. Write a program to search an item in a given list using Linear Search and Binary
Search
9. Write a program for Quick Sort
10. Write a program for Merge Sort
11. Write a program on Binary Search Tree operations(insertion, deletion and
traversals)
12. Write a program for Graph traversals
1. LINKED LIST OPERATIONS
import java.io.*;
class node
{
public int x;
public node next;
}
class LinkedList
{
public node first;
LinkedList()
{
first=new node();
first.next=null;
}
void add (int v)
{
node temp=new node();
temp.x=v;
temp.next=null;
node ptr=first;
while(ptr.next!=null)
ptr=ptr.next;
ptr.next=temp;
}
void insert(int p,int v)
{
node ptr=first,temp;
for(int i=1;i<=p-1;i++)
ptr=ptr.next;
temp=new node();
temp.x=v;
temp.next=ptr.next;
ptr.next=temp;
}
void del(int p)
{
node ptr=first,temp;

Page

for(int i=1;i<=p-1;i++)
ptr=ptr.next;
temp=ptr.next;
ptr.next=ptr.next.next;
temp=null;
}
void show()
{
System.out.println("\nList Elements:");
for(node ptr=first.next;ptr!=null;ptr=ptr.next)
System.out.print("\t"+ptr.x);
}
}
class SListTest
{
public static void main(String as[]) throws Exception
{
String con="";
int x,op,p,v;
LinkedList l1=new LinkedList();
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.println("Enter elements to create");
do
{
x=Integer.parseInt(br.readLine());
l1.add(x);
System.out.print("Add more?(y,n):");
con=br.readLine();
}while(con.equals("y"));
l1.show();
do
{
System.out.println("\n 1.Insert\n 2.Delete \n 3.Display \n 4.Exit");
System.out.println("\nSelect an option:");
op=Integer.parseInt(br.readLine());
if(op==1)
{
System.out.println("Enter Position to insert:");
p= Integer.parseInt(br.readLine());
System.out.println("Enter Value to insert:");
v= Integer.parseInt(br.readLine());
l1.insert(p,v);
}
if(op==2)
{
System.out.println("Enter Position to delete:");
p= Integer.parseInt(br.readLine());
l1.del(p);
}
l1.show();
}while(op<4);
}

. DOUBLE-LINED LIST PROGRAM


import java.io.*;
class node
{
public int x;
public node next;
public node prev;
}
class DoubleLinkedList
{
public node first;
public node last;
DoubleLinkedList()
{
first=new node();
first.next=null;
first.prev=null;
last=first;
}
void add (int v)
{
node temp=new node();
temp.x=v;
temp.next=null;
last.next=temp;
temp.prev=last;
last=temp;

3
Page

}
/* Output: */
Enter elements to create
30
Add more?(y,n):y
40
Add more?(y,n):y
50
Add more?(y,n):n
List Elements:
30 40 50
1.Insert
2.Delete
3.Display
4.Exit
Select an option:1
Enter Position to insert:2
Enter Value to insert:99
List Elements:
30 99 40 50
1.Insert
2.Delete
3.Display
4.Exit
Select an option: 4

Page

}
void insert(int p,int v)
{
node ptr=first,temp;
for(int i=1;i<=p-1;i++)
ptr=ptr.next;
if(ptr.next==null)
add(v);
else
{
temp=new node();
temp.x=v;
temp.next=ptr.next;
ptr.next.prev=temp;
ptr.next=temp;
temp.prev=ptr;
}
}
void del(int p)
{
node ptr=first,temp;
for(int i=1;i<=p-1;i++)
ptr=ptr.next;
if(ptr.next.next==null)
{
temp=last;
last=last.prev;
last.next=null;
}
else
{
temp=ptr.next;
ptr.next=ptr.next.next;
ptr.next.prev=ptr;
}
temp=null;
}
void show()
{
System.out.println("\nList Elements:Left to Right");
for(node ptr=first.next;ptr!=null;ptr=ptr.next)
System.out.print("\t"+ptr.x);
System.out.println("\nList Elements:Right to Left");
for(node ptr=last;ptr.prev!=null;ptr=ptr.prev)
System.out.print("\t"+ptr.x);
}
}
Class DListTest
{
public static void main(String as[]) throws Exception
{
String con="";
int x,op,p,v;

Page

DoubleLinkedList l1=new DoubleLinkedList();


InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.println("Enter elements to create");
do
{
x=Integer.parseInt(br.readLine());
l1.add(x);
System.out.print("Add more?(y,n):");
con=br.readLine();
}while(con.equals("y"));
l1.show();
do
{
System.out.println("\n 1.Insert\n 2.Delete \n 3.Display \n 4.Exit");
System.out.println("\nSelect an option:");
op=Integer.parseInt(br.readLine());
if(op==1)
{
System.out.println("Enter Position to insert:");
p= Integer.parseInt(br.readLine());
System.out.println("Enter Value to insert:");
v= Integer.parseInt(br.readLine());
l1.insert(p,v);
}
if(op==2)
{
System.out.println("Enter Position to delete:");
p= Integer.parseInt(br.readLine());
l1.del(p);
}
l1.show();
}while(op<4);
}
}
/* Output: */
Enter elements to create
30
Add more?(y,n):y
40
Add more?(y,n):y
50
Add more?(y,n):n
List Elements:Left to Right
30 40 50
List Elements:Right to Left
50 40 30
1.Insert
2.Delete
3.Display
4.Exit
Select an option:1
Enter Position to insert:2

6
Page

Enter Value to insert:99


List Elements:Left to Right
30 99 40 50
List Elements:Right to Left
50 40 99 30
1.Insert
2.Delete
3.Display4.Exit Select an option: 4
3. Stack using Linked list
class node
{
public int x;
public node next;
}
class Stack
{
public node top;
Stack()
{
top=null;
}
void push (int v)
{
node temp=new node();
temp.x=v;
temp.next=top;
top=temp;
}
int pop()
{
int v=top.x;
node temp=top;
top=top.next;
temp=null;
return v;
}
}
class StackList
{
public static void main(String as[])
{
Stack s1=new Stack();
s1.push(30);
s1.push(40);
s1.push(50);
System.out.println(s1.pop());
System.out.println(s1.pop());
System.out.println(s1.pop());
}
}
/* Output */
50
40

Page

30
4.STACK USING ARRAY
1. Program to implement PUSH and POP operations on Stack using array method.
class Stack
{
private static int MAX=10;
private int a[]=new int[MAX];
int top;
Stack()
{
top=0;
}
public void push(int v)
{
if(top<max)</max)
a[top++]=v;
else
System.out.println("Overflow");
}
public int pop()
{
if(top>0)
return a[--top];
else
{
System.out.println("Underflow");
return -1;
}
}
}
class StackArray
{
public static void main(String as[])
{
Stack s1=new Stack();
s1.push(30);
s1.push(40);
s1.push(50);
System.out.println(s1.pop());
System.out.println(s1.pop());
System.out.println(s1.pop());
}
}
/* Output */
50
40
30
5. ARTHIMETIC EXPRESSION EVALUTION USING STACK
import java.io.*;
import java.util.*;
class Stack
{

Page

private int a[]=new int[20];


int top;
Stack()
{
top=0;
}
public void push(int v)
{
if(top<20)
a[top++]=v;
else
System.out.println("Overflow");
}
public int pop()
{
if(top>0)
return a[--top];
else
{
System.out.println("Underflow");
return -1;
}
}
public boolean isEmpty()
{
return top==0;
}
}
class Postfix
{
public static void main(String as[]) throws Exception
{
int a,b,c=0;
String str,s;
Stack s1=new Stack();
int i;
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.print("Enter Postfix expression:");
str=br.readLine();
StringTokenizer st=new StringTokenizer(str,",");
while(st.hasMoreTokens())
{
s=st.nextToken();
if(("+-*/").indexOf(s)>=0)
{
b=s1.pop();
a=s1.pop();
switch(s.charAt(0))
{
case '+':c=a+b;
break;
case '-':c=a-b;

Page

break;
case '*':c=a*b;
break;
case '/':c=a/b;
break;
}
s1.push(c);
}
else
s1.push(Integer.parseInt(s));
}
System.out.println("Result="+s1.pop());
}
}
/* Output */
Enter Postfix expression:2,3,*,4,2,/,+
Result=8
6. QUEUES IMPLEMENTATION USING ARRAY
Program to implement insert and delete operations on Queue using array method.
class Queue
{
private static int MAX=10;
private int a[]=new int[MAX];
int front,rear;
Queue()
{
front=rear=0;
}
public void insert(int v)
{
if(rear<max)</max)
a[rear++]=v;
else
System.out.println("Overflow");
}
public int del()
{
if(front!=rear)
return a[front++];
else
{
System.out.println("Underflow");
return -1;
}
}
}
class QArray
{
public static void main(String as[])
{
Queue q1=new Queue();
q1.insert(30);
q1.insert(40);

Page

10

q1.insert(50);
System.out.println(q1.del());
System.out.println(q1.del());
System.out.println(q1.del());
}
}
/* Output */
30
40
50
7.QUEUE OPERATIONS WITH LINKED LIST
Program to implement insert and delete operations on Queue using linked list method
class node
{
public int x;
public node next;
}
class Queue
{
public node front,rear;
Queue()
{
front=rear=null;
}
void insert (int v)
{
node temp=new node();
temp.x=v;
temp.next=null;
if(front==null)
front=rear=temp;
else
{
rear.next=temp;
rear=temp;
}
}
int del()
{
int v=front.x;
node temp=front;
front=front.next;
temp=null;
return v;
}
}
class QueueList
{
public static void main(String as[])
{
Queue q1=new Queue();
q1.insert(30);
q1.insert(40);

11
Page

q1.insert(50);
System.out.println(q1.del());
System.out.println(q1.del());
System.out.println(q1.del());
}
}
/* Output */
30
40
50

8. double ended queue using double linked list


import java.lang.*;
public class ListDeque
{
protected DNode header, trailer; // dummy nodes
protected int size; // number of elements
public ListDeque()
// constructor: initialize an empty deque
{
header = new DNode( 0, null, null );
trailer = new DNode( 0, null, null );
header.setNext(trailer); // make header point to trailer
trailer.setPrev(header); // make trailer point to header
size = 0;
}
public void printDeque()
{
for ( DNode p = header.getNext(); p != trailer; p = p.getNext() )
System.out.print( p.getElement() + " " );
System.out.println();
}
public int size()
{
return size; // replace this line with your code
}
public boolean isEmpty()
{
if(size==0)
{
return true;
}
return false;
//return header.getNaxt()== trailer;
}
public int getFirst() throws EmptyDequeException
{
if(isEmpty())
{

Page

12

throw new EmptyDequeException("Deque is empty.");


}
return header.getNext().getElement();

public int getLast() throws EmptyDequeException


{
// COMPLETE THIS METHOD
if(isEmpty())
{
throw new EmptyDequeException("Deque is empty.");
}
return trailer.getPrev().getElement(); // replace this line with your code
}
public void insertFirst(int e)
{
DNode newNode = new DNode(e, header, header.getNext());
header.getNext().setPrev(newNode);
header.setNext(newNode);
//addAfter(header, e);
}
public void insertLast( int e )
{
DNode newNode = new DNode(e, trailer, trailer.getPrev());
trailer.getPrev().setNext(newNode);
trailer.setPrev(newNode);
//addBefore(trailer, e);
}
public int removeFirst() throws EmptyDequeException
{

if(isEmpty())
{
throw new EmptyDequeException("Deque is empty.");
}
DNode first= header.getNext();
int o = first.getElement();
DNode second = first.getNext();
header.setNext(second);
second.setPrev(header);
size--;
return o; // replace this line with your code

}
public int removeLast() throws EmptyDequeException
{
if(isEmpty())
{
throw new EmptyDequeException("Deque is empty.");
}
DNode last = trailer.getPrev();

13
Page

int o = last.getElement();
DNode secondtolast = last.getPrev();
trailer.setPrev(secondtolast);
secondtolast.setNext(trailer);
size--;
return o;
}

} // end class
output
adding at front: 34
adding at front: 67
adding at front: 29
adding at front: 765
removed from front: 765
removed from front: 29
removed from front: 67
underflow!! unable to remove. - See more at:
8.Linear search and binary search
/*
Program to search for a number in an array entered by the user using
either Linear Search or Binary Search.
*/
import java.io.*;
class searchArray
{
int a[];
int n;
static BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
public searchArray(int nn) // Constructor
{
a = new int[nn];
n = nn;
}
public static void main(String args[]) throws IOException
{
System.out.print("\nEnter the size of the array : ");
int nn = Integer.parseInt(br.readLine());
searchArray call = new searchArray(nn);
System.out.println("\nEnter " +nn +" elements :");
call.readArray();
// Ask for the search technique
System.out.println("Choose Search Technique :\n");
System.out.println("1 : Linear Search");
System.out.println("2 : Binary Search (the array should be
sorted in ascending order)");
System.out.print("\nYour Choice : ");
int choice = Integer.parseInt(br.readLine());
int v;
switch(choice)
{

Page

14

case 1:
System.out.print("\nEnter the number to be searched : ");
v = Integer.parseInt(br.readLine());
call.linearSearch(v);
break;
case 2:
System.out.print("\nEnter the number to be searched : ");
v = Integer.parseInt(br.readLine());
call.binarySearch(v);
break;
default :
System.out.println("\nInvalid Choice !");
break;
}
}
public void readArray() throws IOException
{
for(int i=0;i<n;i++)
a[i] = Integer.parseInt(br.readLine());
}
public void linearSearch(int v)
{
int f=-1;
for(int i=0;i<n;i++)
{
if(a[i]==v)
{
f=i;
break;
}
}
if(f==-1)
System.out.println("\n" +v +" NOT found !");
else
System.out.println("\n" +v +" is in location " +f);
}
public void binarySearch(int v)
{
int f=-1;
int l=0,m=0,u=n-1;
while(l<=u && f==-1)
{
m = (l+u)/2;
if(a[m]==v)
f = m;
else
if(a[m]>v)
u = m-1;
else
l = m+1;
}
if(f==-1)
7System.out.println("\n" +v +" NOT found !");

Page

15

else
System.out.println("\n" +v +" is in location " +m);
}
}
9. Quick sort implementation
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
public class QuickSort {

private static void swap(int[] a, int i, int j) {


int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
private static void quicksort(int list[], int from, int to) {
// If the indexes cross, then we've sorted the whole array.
if (from >= to) {
return;
}
int pivot = list[from];
int i = from - 1;
int j = to + 1;
while (i < j) {
// Keep incrementing from the start of the range so long as the
// values are less than the pivot.
i++;
while (list[i] < pivot) { i++; }
// Keep decrementing from the end of the range so long as the values
// are greater than the pivot.
j--;
while (list[j] > pivot) { j--; }
// So long at the indexes have not crossed, swap the pivot with the
// value that was out of place.
if (i < j) {
swap(list, i, j);
}
}
// Recursively sort the two portions of the array
quicksort(list, from, j);
quicksort(list, j + 1, to);
}
// Helper method that kicks off the recursive quicksort method
public static int[] quicksort(int [] list) {

Page

16

quicksort(list, 0, list.length-1);
return list;

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


{

String list="";
int i=0,n=0;
QuickSort s= new QuickSort();
ArrayList<Integer> arrlist=new ArrayList<Integer>();
System.out.println(" ");
System.out.println(" ");
System.out.println("Please enter the list of elements,one element per line");
System.out.println(" write 'STOP' when list is completed ");
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
while(!(list=bf.readLine()).equalsIgnoreCase("stop")){
int intelement=Integer.parseInt(list);
arrlist.add(intelement);
}
int elementlist[] = new int[arrlist.size()];
Iterator<Integer> iter = arrlist.iterator();
for (int j=0;iter.hasNext();j++) {
elementlist[j] = iter.next();
}

elementlist=quicksort(elementlist);
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println("Values after Quick Sort : ");
for (int j=0;j<elementlist.length;j++) {
System.out.println(elementlist[j]+" ");
}

}
10. java program to implement merge sort
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
public class MergeSort {

public static int[] mergeSort(int [] list) {


if (list.length <= 1) {
return list;

17

Page

// Split the array in half


int[] first = new int[list.length / 2];
int[] second = new int[list.length - first.length];
System.arraycopy(list, 0, first, 0, first.length);
System.arraycopy(list, first.length, second, 0, second.length);
// Sort each half
mergeSort(first);
mergeSort(second);
// Merge the halves together, overwriting the original array
merge(first, second, list);
return list;
}
private static void merge(int[] first, int[] second, int [] result) {
// Merge both halves into the result array
// Next element to consider in the first array
int iFirst = 0;
// Next element to consider in the second array
int iSecond = 0;
// Next open position in the result
int j = 0;
// As long as neither iFirst nor iSecond is past the end, move the
// smaller element into the result.
while (iFirst < first.length && iSecond < second.length) {
if (first[iFirst] < second[iSecond]) {
result[j] = first[iFirst];
iFirst++;
} else {
result[j] = second[iSecond];
iSecond++;
}
j++;
}
// copy what's left
System.arraycopy(first, iFirst, result, j, first.length - iFirst);
System.arraycopy(second, iSecond, result, j, second.length - iSecond);
}

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


{
String list="";
int i=0,n=0;
MergeSort s= new MergeSort();
ArrayList<Integer> arrlist=new ArrayList<Integer>();
System.out.println(" ");

Page

18

System.out.println(" ");
System.out.println("Please enter the list of elements,one element per line");
System.out.println(" write 'STOP' when list is completed ");
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
while(!(list=bf.readLine()).equalsIgnoreCase("stop")){
int intelement=Integer.parseInt(list);
arrlist.add(intelement);
}
int elementlist[] = new int[arrlist.size()];
Iterator<Integer> iter = arrlist.iterator();
for (int j=0;iter.hasNext();j++) {
elementlist[j] = iter.next();
}

elementlist=mergeSort(elementlist);
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println("Values after Merge Sort : ");
for (int j=0;j<elementlist.length;j++) {
System.out.println(elementlist[j]+" ");
}

}
11.Write a program on Binary Search Tree operations(insertion, deletion and
traversals)
/*
* Java Program to Implement Binary Search Tree
*/
import java.util.Scanner;
/* Class BSTNode */
class BSTNode
{
BSTNode left, right;
int data;
/* Constructor */
public BSTNode()
{
left = null;
right = null;
data = 0;
}
/* Constructor */
public BSTNode(int n)
{
left = null;
right = null;

}
/* Class BST */
class BST
{
private BSTNode root;
/* Constructor */
public BST()
{
root = null;
}
/* Function to check if tree is empty */
public boolean isEmpty()
{
return root == null;
}
/* Functions to insert data */
public void insert(int data)
{
root = insert(root, data);

19
Page

data = n;
}
/* Function to set left node */
public void setLeft(BSTNode n)
{
left = n;
}
/* Function to set right node */
public void setRight(BSTNode n)
{
right = n;
}
/* Function to get left node */
public BSTNode getLeft()
{
return left;
}
/* Function to get right node */
public BSTNode getRight()
{
return right;
}
/* Function to set data to node */
public void setData(int d)
{
data = d;
}
/* Function to get data from node */
public int getData()
{
return data;
}

Page

20

}
/* Function to insert data recursively */
private BSTNode insert(BSTNode node, int data)
{
if (node == null)
node = new BSTNode(data);
else
{
if (data <= node.getData())
node.left = insert(node.left, data);
else
node.right = insert(node.right, data);
}
return node;
}
/* Functions to delete data */
public void delete(int k)
{
if (isEmpty())
System.out.println("Tree Empty");
else if (search(k) == false)
System.out.println("Sorry "+ k +" is not present");
else
{
root = delete(root, k);
System.out.println(k+ " deleted from the tree");
}
}
private BSTNode delete(BSTNode root, int k)
{
BSTNode p, p2, n;
if (root.getData() == k)
{
BSTNode lt, rt;
lt = root.getLeft();
rt = root.getRight();
if (lt == null && rt == null)
return null;
else if (lt == null)
{
p = rt;
return p;
}
else if (rt == null)
{
p = lt;
return p;
}
else
{
p2 = rt;
p = rt;
while (p.getLeft() != null)

}
}
if (k < root.getData())
{
n = delete(root.getLeft(), k);
root.setLeft(n);
}
else
{
n = delete(root.getRight(), k);
root.setRight(n);
}
return root;

21
Page

p = p.getLeft();
p.setLeft(lt);
return p2;

}
/* Functions to count number of nodes */
public int countNodes()
{
return countNodes(root);
}
/* Function to count number of nodes recursively */
private int countNodes(BSTNode r)
{
if (r == null)
return 0;
else
{
int l = 1;
l += countNodes(r.getLeft());
l += countNodes(r.getRight());
return l;
}
}
/* Functions to search for an element */
public boolean search(int val)
{
return search(root, val);
}
/* Function to search for an element recursively */
private boolean search(BSTNode r, int val)
{
boolean found = false;
while ((r != null) && !found)
{
int rval = r.getData();
if (val < rval)
r = r.getLeft();
else if (val > rval)
r = r.getRight();
else
{

22

}
found = search(r, val);
}
return found;

}
/* Function for inorder traversal */
public void inorder()
{
inorder(root);
}
private void inorder(BSTNode r)
{
if (r != null)
{
inorder(r.getLeft());
System.out.print(r.getData() +" ");
inorder(r.getRight());
}
}
/* Function for preorder traversal */
public void preorder()
{
preorder(root);
}
private void preorder(BSTNode r)
{
if (r != null)
{
System.out.print(r.getData() +" ");
preorder(r.getLeft());
preorder(r.getRight());
}
}
/* Function for postorder traversal */
public void postorder()
{
postorder(root);
}
private void postorder(BSTNode r)
{
if (r != null)
{
postorder(r.getLeft());
postorder(r.getRight());
System.out.print(r.getData() +" ");
}
}

/* Class BinarySearchTree */
public class BinarySearchTree

Page

found = true;
break;

23

public static void main(String[] args)


{
Scanner scan = new Scanner(System.in);
/* Creating object of BST */
BST bst = new BST();
System.out.println("Binary Search Tree Test\n");
char ch;
/* Perform tree operations */
do
{
System.out.println("\nBinary Search Tree Operations\n");
System.out.println("1. insert ");
System.out.println("2. delete");
System.out.println("3. search");
System.out.println("4. count nodes");
System.out.println("5. check empty");

Page

int choice = scan.nextInt();


switch (choice)
{
case 1 :
System.out.println("Enter integer element to insert");
bst.insert( scan.nextInt() );
break;
case 2 :
System.out.println("Enter integer element to delete");
bst.delete( scan.nextInt() );
break;
case 3 :
System.out.println("Enter integer element to search");
System.out.println("Search result : "+ bst.search( scan.nextInt() ));
break;
case 4 :
System.out.println("Nodes = "+ bst.countNodes());
break;
case 5 :
System.out.println("Empty status = "+ bst.isEmpty());
break;
default :
System.out.println("Wrong Entry \n ");
break;
}
/* Display tree */
System.out.print("\nPost order : ");
bst.postorder();
System.out.print("\nPre order : ");
bst.preorder();
System.out.print("\nIn order : ");
bst.inorder();
System.out.println("\nDo you want to continue (Type y or n) \n");
ch = scan.next().charAt(0);

24

} while (ch == 'Y'|| ch == 'y');

Page

12.Graph Traversals: Non-Recursive BFS************************


class Queue
{
private final int SIZE = 20;
private int[] st;
private int front,rear;
public Queue()
{
st = new int[SIZE];
front = rear= 0;
}
public void enQueue(int j)
{
st[rear++] = j;
}
public int deQueue()
{
return st[front++];
}
public int peek()
{
return st[front];
}
public boolean isEmpty()
{
if (front==rear) return true;
else return false;
}
}
class Vertex
{
public char label;
public boolean visited;
public Vertex(char label)
{
this.label = label;
visited = false;
}
}
class Graph
{
private final int MAX = 20;
private Vertex vertex[];
private int adjMat[][];
private int n;
private Queue stk;
public Graph()
{

Page

25

vertex = new Vertex[MAX];


adjMat = new int[MAX][MAX];
n = 0;
for(int y=0; y<MAX; y++)
for(int x=0; x<MAX; x++)
adjMat[x][y] = 0;
stk = new Queue();
}
public void addVertex(char lab)
{
vertex[n++] = new Vertex(lab);
}
public void addEdge(int source, int destination)
{
adjMat[source][destination] = 1;
adjMat[destination][source] = 1;
}
public void displayVertex(int v)
{
System.out.print(vertex[v].label);
}
public void bfs()
{
vertex[0].visited = true;
displayVertex(0);
stk.enQueue(0);
while( !stk.isEmpty() )
{
int v = getUnvisitedVertex( stk.peek() );
if(v == -1)
stk.deQueue();
else
{
vertex[v].visited = true;
displayVertex(v);
stk.enQueue(v);
}
}
for(int j=0; j<n; j++)
vertex[j].visited = false;
}
public int getUnvisitedVertex(int v)
{
for(int j=0; j<n; j++)
if(adjMat[v][j]==1 && vertex[j].visited==false)
return j;
return -1;
}
}
class BFS
{
public static void main(String[] args)
{

Page

26

Graph g = new Graph(); // Assume 0,1,2,3,4 are the indexes of A,B,C,D,E respectively.
g.addVertex('A');
g.addVertex('B');
g.addVertex('C');
g.addVertex('D');
g.addVertex('E');
g.addEdge(0, 1);
g.addEdge(0, 4);
g.addEdge(4, 1);
g.addEdge(1, 3);
g.addEdge(1, 2);
g.addEdge(2, 3);
g.addEdge(3, 4);
System.out.print("Visits: ");
g.bfs();
System.out.println();
}
}
Graph Traversals: Non-Recursive DFS************************
class Stack
{
private final int SIZE = 20;
private int[] st;
private int top;
public Stack()
{
st = new int[SIZE];
top = -1;
}
public void push(int j)
{
st[++top] = j;
}
public int pop()
{
return st[top--];
}
public int peek()
{
return st[top];
}
public boolean isEmpty()
{
return (top == -1);
}
}
class Vertex
{
public char label;
public boolean visited;
public Vertex(char label)
{
this.label = label;

Page

27

visited = false;
}
}
class Graph
{
private final int MAX = 20;
private Vertex vertex[];
private int adjMat[][];
private int n;
private Stack stk;
public Graph()
{
vertex = new Vertex[MAX];
adjMat = new int[MAX][MAX];
n = 0;
for(int y=0; y<MAX; y++)
for(int x=0; x<MAX; x++)
adjMat[x][y] = 0;
stk = new Stack();
}
public void addVertex(char lab)
{
vertex[n++] = new Vertex(lab);
}
public void addEdge(int source, int destination)
{
adjMat[source][destination] = 1;
adjMat[destination][source] = 1;
}
public void displayVertex(int v)
{
System.out.print(vertex[v].label);
}
public void dfs()
{
vertex[0].visited = true;
displayVertex(0);
stk.push(0);
while( !stk.isEmpty() )
{
int v = getUnvisitedVertex( stk.peek() );
if(v == -1)
stk.pop();
else
{
vertex[v].visited = true;
displayVertex(v);
stk.push(v);
}
}
for(int j=0; j<n; j++)
vertex[j].visited = false;
}

Page

28

public int getUnvisitedVertex(int v)


{
for(int j=0; j<n; j++)
if(adjMat[v][j]==1 && vertex[j].visited==false)
return j;
return -1;
}
}
class DFS
{
public static void main(String[] args)
{
Graph g = new Graph(); // Assume 0,1,2,3,4 are the indexes of A,B,C,D,E respectively.
g.addVertex('A');
g.addVertex('B');
g.addVertex('C');
g.addVertex('D');
g.addVertex('E');
g.addEdge(0, 1);
g.addEdge(0, 4);
g.addEdge(4, 1);
g.addEdge(1, 3);
g.addEdge(1, 2);
g.addEdge(2, 3);
g.addEdge(3, 4);
System.out.print("Visits: ");
g.dfs();
System.out.println();
}
}

You might also like