# Page

1

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
import java.io.*;
class node
{
public int x;
public node next;
}
{
public node first;
{
first=new node();
first.next=null;
}
{
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

2

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;
System.out.println("Enter elements to create");
do
{
}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:");
if(op==1)
{
System.out.println("Enter Position to insert:");
System.out.println("Enter Value to insert:");
l1.insert(p,v);
}
if(op==2)
{
System.out.println("Enter Position to delete:");
l1.del(p);
}
l1.show();
}while(op<4);
}

n):y 50 Add more?(y. public node next. } void add (int v) { node temp=new node().n):n List Elements: 30 40 50 1.Insert 2. temp.next=null. DOUBLE-LINED LIST PROGRAM import java. DoubleLinkedList() { first=new node()..Delete 3.Display 4. first.io.Exit Select an option:1 Enter Position to insert:2 Enter Value to insert:99 List Elements: 30 99 40 50 1.next=null. temp.*. temp. last.x=v.Exit Select an option: 4 . public node prev.prev=null. public node last. 3 Page } /* Output: */ Enter elements to create 30 Add more?(y. last=first.Delete 3.n):y 40 Add more?(y.Display 4.prev=last. class node { public int x. } class DoubleLinkedList { public node first.Insert 2. first.next=temp. last=temp.

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

System. top=temp.next=top.println(s1. } void push (int v) { node temp=new node().pop()).println(s1.Exit Select an option: 4 3.push(50).out.pop()).next. } } class StackList { public static void main(String as[]) { Stack s1=new Stack().x=v. } int pop() { int v=top.Display4. top=top.x.push(40). Stack using Linked list class node { public int x. return v. } class Stack { public node top. temp.pop()).out. System.Insert 2. node temp=top. System.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. s1.println(s1.out. temp=null. temp. s1.push(30). } } /* Output */ 50 40 . Stack() { top=null. public node next.Delete 3. s1.

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

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

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

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

getNext() ) System. p != trailer.insert(50). System. // number of elements public ListDeque() // constructor: initialize an empty deque { header = new DNode( 0.out. System.*. } public int size() { return size. public class ListDeque { protected DNode header.out. p = p.setPrev(header).lang.del()). null ). } public void printDeque() { for ( DNode p = header. System.getNaxt()== trailer. null.println(q1.out. // dummy nodes protected int size.getElement() + " " ).println(q1. double ended queue using double linked list import java.println(). trailer. // make header point to trailer trailer.del()).del()). System. } public int getFirst() throws EmptyDequeException { if(isEmpty()) { . } } /* Output */ 30 40 50 8. //return header.println(q1.11 Page q1. null.getNext(). trailer = new DNode( 0. } return false.out.out. null ).setNext(trailer).print( p. // replace this line with your code } public boolean isEmpty() { if(size==0) { return true. header. // make trailer point to header size = 0.

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

} // Helper method that kicks off the recursive quicksort method public static int[] quicksort(int [] list) { .1.Page 15 else System. j--. } // Keep decrementing from the end of the range so long as the values // are greater than the pivot. a[i] = a[j]. int i = from .io.InputStreamReader. i.io.out. while (i < j) { // Keep incrementing from the start of the range so long as the // values are less than the pivot.BufferedReader.util. while (list[j] > pivot) { j--. j). } } // Recursively sort the two portions of the array quicksort(list. while (list[i] < pivot) { i++. a[j] = temp. int from. import java.Iterator. from. swap the pivot with the // value that was out of place. int i.println("\n" +v +" is in location " +m). } // So long at the indexes have not crossed. quicksort(list. import java. } int pivot = list[from]. if (i < j) { swap(list.util. } private static void quicksort(int list[]. int to) { // If the indexes cross. import java. if (from >= to) { return. int j) { int temp = a[i]. int j = to + 1. then we've sorted the whole array. j + 1. Quick sort implementation import java. i++. to). } } 9. j). public class QuickSort { private static void swap(int[] a.ArrayList.

list. return list.one element per line"). for (int j=0. public class MergeSort { public static int[] mergeSort(int [] list) { if (list. while(!(list=bf.iterator(). System.io. System.out. 0.iter.ArrayList. System.Iterator.parseInt(list). arrlist.println(" ").in)).equalsIgnoreCase("stop")){ int intelement=Integer.hasNext(). for (int j=0.out. import java. import java.Page } 16 quicksort(list.n=0.out. System.j++) { elementlist[j] = iter. System.BufferedReader.println("Values after Quick Sort : ").util. } } 10.println(" write 'STOP' when list is completed ").out.println("Please enter the list of elements.println(" "). BufferedReader bf=new BufferedReader(new InputStreamReader(System.out.io.println(" ").println(" ").j++) { System.add(intelement). public static void main(String args[]) throws Exception { String list="". .size()]. System.out.j<elementlist.out. System.readLine()). ArrayList<Integer> arrlist=new ArrayList<Integer>(). java program to implement merge sort import java.InputStreamReader.util. } } elementlist=quicksort(elementlist). Iterator<Integer> iter = arrlist.out.length.println(" "). System. QuickSort s= new QuickSort(). import java. } int elementlist[] = new int[arrlist.length <= 1) { return list.next().out.length-1).println(elementlist[j]+" "). int i=0.

iFirst). iFirst. overwriting the original array merge(first. .arraycopy(second. first. // Merge the halves together. // Next open position in the result int j = 0. System. } j++. 0. 0. ArrayList<Integer> arrlist=new ArrayList<Integer>(). // Sort each half mergeSort(first).first. j. first.length && iSecond < second. int[] second. result.out. } else { result[j] = second[iSecond].arraycopy(list. System. return list. 0.length).println(" "). list). System. MergeSort s= new MergeSort(). result.length / 2]. iFirst++.arraycopy(list. } // copy what's left System. int[] second = new int[list. // As long as neither iFirst nor iSecond is past the end. 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. second. } private static void merge(int[] first.iSecond).17 } Page // Split the array in half int[] first = new int[list. j.length . while (iFirst < first.length. System.length) { if (first[iFirst] < second[iSecond]) { result[j] = first[iFirst].n=0. first. move the // smaller element into the result. int i=0. second. mergeSort(second). first.length .length).length . second. iSecond. iSecond++.arraycopy(first.length]. } public static void main(String args[]) throws Exception { String list="". second.

/* Constructor */ public BSTNode() { left = null.println(" ").hasNext().println(" "). right.out.length. /* Class BSTNode */ class BSTNode { BSTNode left.j<elementlist.out.println("Please enter the list of elements.out.iter. System.in)).println(" ").Page 18 System.iterator(). } /* Constructor */ public BSTNode(int n) { left = null.size()]. .next().Write a program on Binary Search Tree operations(insertion. System.equalsIgnoreCase("stop")){ int intelement=Integer.one element per line").println(" "). right = null. System. while(!(list=bf.j++) { System. System. arrlist.println(" write 'STOP' when list is completed ").j++) { elementlist[j] = iter.out. right = null. for (int j=0.Scanner.out.add(intelement). System. Iterator<Integer> iter = arrlist.parseInt(list). } } elementlist=mergeSort(elementlist).println("Values after Merge Sort : ").println(elementlist[j]+" "). data = 0. System.out.out. deletion and traversals) /* * Java Program to Implement Binary Search Tree */ import java.readLine()). for (int j=0.util.out. BufferedReader bf=new BufferedReader(new InputStreamReader(System. int data. } } 11. } int elementlist[] = new int[arrlist.

/* Constructor */ public BST() { root = null. } . } /* Functions to insert data */ public void insert(int data) { root = insert(root. 19 Page data = n. } /* Function to set data to node */ public void setData(int d) { data = d. } /* Function to set right node */ public void setRight(BSTNode n) { right = n. } /* Function to set left node */ public void setLeft(BSTNode n) { left = n.} /* Class BST */ class BST { private BSTNode root. data). } /* Function to get left node */ public BSTNode getLeft() { return left. } /* Function to get right node */ public BSTNode getRight() { return right. } /* Function to get data from node */ public int getData() { return data. } /* Function to check if tree is empty */ public boolean isEmpty() { return root == null.

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

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

} private void inorder(BSTNode r) { if (r != null) { inorder(r. } } /* Function for inorder traversal */ public void inorder() { inorder(root).out. preorder(r.getLeft()).print(r. break. .getData() +" "). System. } private void preorder(BSTNode r) { if (r != null) { System. postorder(r.getLeft()).getData() +" "). } return found. preorder(r. } } /* Class BinarySearchTree */ public class BinarySearchTree Page found = true. } private void postorder(BSTNode r) { if (r != null) { postorder(r.getRight()).getData() +" ").getLeft()). val).22 } found = search(r.out.getRight()).out.getRight()). } } /* Function for postorder traversal */ public void postorder() { postorder(root). } } /* Function for preorder traversal */ public void preorder() { preorder(root). inorder(r.print(r.print(r. System.

countNodes()).println("Binary Search Tree Test\n"). break.isEmpty()).println("5. bst.println("4.nextInt() ).postorder().println("Enter integer element to insert").inorder().charAt(0). bst.out.out. case 3 : System. System. delete"). insert ").in).println("Search result : "+ bst.out.out. switch (choice) { case 1 : System.search( scan.println("1. bst. System.out.out.preorder().nextInt().print("\nIn order : ").out. break.out. break. } /* Display tree */ System. check empty").print("\nPre order : "). case 2 : System.out. System.insert( scan. case 4 : System.nextInt() )).out.out.out. System.println("2. default : System.println("Enter integer element to search").next().println("Wrong Entry \n "). search").nextInt() ).println("Nodes = "+ bst. System. count nodes"). /* Perform tree operations */ do { System. break.out. bst.print("\nPost order : "). break. System. System.println("\nDo you want to continue (Type y or n) \n").out.println("\nBinary Search Tree Operations\n").23 public static void main(String[] args) { Scanner scan = new Scanner(System. ch = scan. bst. System. System. case 5 : System.println("Empty status = "+ bst. Page { int choice = scan.out. System.delete( scan. break.out. .out.out.println("3. char ch. /* Creating object of BST */ BST bst = new BST().println("Enter integer element to delete").

private int adjMat[][].rear. public Queue() { st = new int[SIZE].24 } } while (ch == 'Y'|| ch == 'y'). } public void enQueue(int j) { st[rear++] = j. private Vertex vertex[]. } public int deQueue() { return st[front++]. public boolean visited. } public int peek() { return st[front]. private int front. } } class Vertex { public char label.label = label. else return false.Graph Traversals: Non-Recursive BFS************************ class Queue { private final int SIZE = 20. public Vertex(char label) { this. } public boolean isEmpty() { if (front==rear) return true. private Queue stk. public Graph() { . front = rear= 0. private int[] st. visited = false. private int n. } } class Graph { private final int MAX = 20. Page } 12.

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