Java Record

95
HT.NO: 08F41F0040 Program No:-1 Program Name: Write a Java program that prints all real solutions to the quadratic equation ax 2 + bx + c =0. Read in a,b,c and use the quadratic formula. If the discriminate b 2 - 4ac is negative; display a message stating that there are no real solutions. class roots { public static void main(String args[ ]) { int a,b,c,n; double sol,root1,root2; a=Integer.parseInt(args[0]); b=Integer.parseInt(args[1]); c=Integer.parseInt(args[2]); n=(b*b)-(4*a*c); sol=Math.sqrt(n); if(n>0) { System.out.println("The roots are real and equal"); root1=(-b+Math.sqrt(n))/2*a; root2=(-b-Math.sqrt(n))/2*a; System.out.println("The solution set is ("+root1+","+root2+")"); } else { System.out.println("The solution is not exit"); } } /**********Output********* D:\dslab>javac roots.java D:\dslab>java roots 1 7 6 The roots are real and equal The solution set is (-1.0,-6.0) D:\dslab>java roots 1 2 1 No real solutions exits*/ Data Structures through java Lab Department of M.C.A

Transcript of Java Record

Page 1: Java Record

HT.NO: 08F41F0040

Program No:-1Program Name: Write a Java program that prints all real solutions to the quadratic equation ax2 + bx + c =0. Read in a,b,c and use the quadratic formula. If the discriminate b2

- 4ac is negative; display a message stating that there are no real solutions. class roots{ public static void main(String args[ ]){ int a,b,c,n; double sol,root1,root2; a=Integer.parseInt(args[0]); b=Integer.parseInt(args[1]); c=Integer.parseInt(args[2]); n=(b*b)-(4*a*c); sol=Math.sqrt(n);if(n>0){System.out.println("The roots are real and equal");root1=(-b+Math.sqrt(n))/2*a;root2=(-b-Math.sqrt(n))/2*a;System.out.println("The solution set is ("+root1+","+root2+")");}else{System.out.println("The solution is not exit");}}

/**********Output*********D:\dslab>javac roots.java

D:\dslab>java roots 1 7 6 The roots are real and equal The solution set is (-1.0,-6.0)D:\dslab>java roots 1 2 1 No real solutions exits*/

Program No:-2

Data Structures through java Lab Department of M.C.A

Page 2: Java Record

HT.NO: 08F41F0040

Program Name: The Fibonacci sequence is defined by the following rule. The first two values in the sequence are 1 and 1. Every subsequent value is the run of the two values preceding it. Write a Java program that uses both recursive and non-recursive functions to print the nth value in the Fibonacci sequence.

/* Fibonacci series by using recursion*/

import java.io.*;class fib1{public static void main(String args[])throws IOException{fib1 f=new fib1();BufferedReader br=new BufferedReader (new InputStreamReader(System.in));System.out.print("Enter the series range : ");int n=Integer.parseInt(br.readLine());System.out.print("Enter the sequence position : ");int m=Integer.parseInt(br.readLine());for(int i=0;i<=n;i++) { if(i==m) System.out.print("The fibonacci number at position "+m+" is "+f.fib(i)); }}

int fib(int n){ if(n==1) return 1; if (n==0) return 0; return (fib(n-1)+fib(n-2));}}

/***********OUTPUT**********

D:\dslab\varun>javac fib1.javaD:\dslab\varun>java fib1Enter the series range : 20

Data Structures through java Lab Department of M.C.A

Page 3: Java Record

HT.NO: 08F41F0040

Enter the sequence position : 9The fibonacci number at position 9 is 34 D:\dslab\varun>java fib1Enter the series range : 30Enter the sequence position : 7The fibonacci number at position 7 is 13 */

/* Fibonacci series by using non-recursion*/

import java.io.*;class fib{int prev=0,cur=1;public static void main(String args[])throws IOException{int n,i,j;fib f=new fib();BufferedReader br=new BufferedReader (new InputStreamReader(System.in));System.out.println("Series Range");n=Integer.parseInt(br.readLine());System.out.println("Enter the sequenc position ");j=Integer.parseInt(br.readLine());i=1;while(true){i++;int k=f.fibonac();if(k<n){if(j<=i)if(i==j){System.out.println("the fibonaci no. of"+j+"is "+k);break;}}else if(j> i){System.out.println("not in fib range");break;}}}int fibonac()

Data Structures through java Lab Department of M.C.A

Page 4: Java Record

HT.NO: 08F41F0040

{

int temp=prev;prev=cur;cur=cur+temp;return cur;}}

/**********OUTPUT**********

D:\dslab>javac fib.javaD:\dslab>java fibSeries Range10Enter the sequenc position5the fibonaci number of 6 is 8.

D:\dslab>java fibSeries Range10Enter the sequenc position9not in fib range

*/

Program No:-3Program Name: Write a Java program that prompts the user for an integer and then prints out all prime numbers up to that Integer.

import java.io.*;class prime{public static void main(String args[])throws IOException{int count=0,n,i,j;BufferedReader br=new BufferedReader(new InputStreamReader(System.in));n=Integer.parseInt(args[0]);for(i=2;i<=n;i++){count=0;for(j=1;j<=n;j++)

Data Structures through java Lab Department of M.C.A

Page 5: Java Record

HT.NO: 08F41F0040

{if(i%j==0){count++;}}if(count==2)System.out.print(" "+i);}}}

/**********Output**********

D:\dslab>javac prime.java

D:\dslab>java prime 5 The prime number series is 2 3 5D:\dslab>java prime 15 The prime number series is 2 3 5 7 11 13 */

Program No:-4Program Name: Writa a Java program that checks whether a given string is a palindrome or not Ex: MADAM is a palindrome.

import java.io.*;class palindrome{public static void main(String args[ ])throws IOException{String Str2=new String();String Str1=new String();BufferedReader br=new BufferedReader(new InputStreamReader(System.in));System.out.print("Enter string : ");Str1=br.readLine();for(int i=(Str1.length())-1;i>=0;i--) Str2=Str2+Str1.charAt(i);if(Str1.equals(Str2))System.out.println(Str1+ " is palindrome");elseSystem.out.println(Str1+ " is not palindrome");

Data Structures through java Lab Department of M.C.A

Page 6: Java Record

HT.NO: 08F41F0040

}} /********Output************

D:\dslab>javac palindrome.javaD:\dslab>java palindrome Enter the string : MALAYALAM MALAYALAM is palindrome

D:\dslab>java palindromeEnter the string: SREENATHSREENATH is not palindrome*/

Program No:-5Program Name: Write a Java program for sorting a given list of names in ascending order.

import java.io.*;class sorting{public static void main(String args[])throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in));System.out.print("enter the array size : ");int n=Integer.parseInt (br.readLine());String Str[]= new String[n];System.out.println("enter the name");for(int k=0;k<n;k++) Str[k]=br.readLine();for(int i=0;i<Str.length;i++)for(int j=i+1;j<Str.length;j++){if(Str[j].compareTo(Str[i])<0){String temp=Str[i];Str[i]=Str[j];Str[j]=temp;}}

Data Structures through java Lab Department of M.C.A

Page 7: Java Record

HT.NO: 08F41F0040

System.out.println(" stings ascending order is");for(int i=0;i<n;i++)System.out.println(" "+Str[i]);}}

/*********Output**********

D:\dslab>javac sorting.javaD:\dslab>java sorting 5 Enter the array size : 5 Enter the names : Sreenath Hari Chandu Varun Bhanu Stings ascending order is Bhanu Chandu Hari Sreenath Varun

*/

Data Structures through java Lab Department of M.C.A

Page 8: Java Record

HT.NO: 08F41F0040

Program No:-6Program Name: Write a Java program to multiply two given matrices

import java.io.*;class matrix1{public static void main(String args[])throws IOException{BufferedReader br=new BufferedReader (new InputStreamReader(System.in));System.out.println("enter array size");int n=Integer.parseInt(br.readLine());int a[][]=new int[n][n];int b[][]=new int[n][n];int c[][]=new int[n][n];System.out.println("enter matrix A");for(int i=0;i<n;i++){for(int j=0;j<n;j++){a[i][j]=Integer.parseInt(br.readLine());}}System.out.println("enter matrix B");for(int i=0;i<n;i++){for(int j=0;j<n;j++){b[i][j]=Integer.parseInt(br.readLine());}}System.out.println("Matrix multiplication is ");for(int i=0;i<n;i++){for(int j=0;j<n;j++){c[i][j]=0;for(int k=0;k<n;k++)

Data Structures through java Lab Department of M.C.A

Page 9: Java Record

HT.NO: 08F41F0040

{c[i][j]=c[i][j]+(a[i][k]*b[k][j]);}System.out.println(c[i][j]+" ");}}}}

/*********Output*********

D:\dslab>javac matrix1.javaD:\dslab>java matrix1 Enter array size 2 Enter matrix A 2 2 2 2 Enter matrix B 2 2 2 2 Matrix multiplication of A and B is 8 8 8 8*/

Data Structures through java Lab Department of M.C.A

Page 10: Java Record

HT.NO: 08F41F0040

Program No:-7 Program Name: Write a Java program reads a line integers, and then displays each integer, and the sum of all integers (use String Tokenizer class)

/* To find sum of numbers using StringTokenizer*/

import java.io.*;import java.util.*;class tokens{

public static void main(String args[])throws IOException{int n=0;BufferedReader br=new BufferedReader(new InputStreamReader(System.in));String a=br.readLine();StringTokenizer stoken=new StringTokenizer(a);while(stoken.hasMoreTokens()){ n=n+Integer.parseInt(stoken.nextToken());}System.out.println("sum of no: "+n);}}

/*********Output************

D:\dslab>javac tokens.javaD:\dslab>java tokens : 6 8 10 Sum of numbers is : 24

*/

Program No:8Program Name :Write a Java program reads a file name from the user then displays information about whether the file exists,

Data Structures through java Lab Department of M.C.A

Page 11: Java Record

HT.NO: 08F41F0040

whether the file is readable, whether the file is writable, the type of file and the length of the file in bytes.

import java.io.*;class Filedemo{static void print(String s){System.out.println(s);}public static void main(String args[]){String filename=args[0];File f1=new File(filename);print("filename :"+f1.getName());print("pathname:"+f1.getPath());print(f1.exists()?"exist": "Does not exist");print(f1.canWrite()? "Writable": "is not writable");print(f1.canRead()?"readable": "is not readable");print("filesize:"+f1.length()+"Bytes");}}

/********************OUTPUT*****************************************D:\dslab>javac Filedemo.javaD:\dslab>java Filedemo fib.javafilename :fib.javapathname:fib.javaexistWritablereadablefilesize:810Bytes

D:\dslab>java Filedemo fibretw.javafilename :fibretw.javapathname:fibretw.javaDoes not existis not writableis not readable filesize:0Bytes */

Program No:-9Program Name: Write a Java program that reads a file and displays a file and displays the file on the screen, with a line number before each line import java.io.*;

Data Structures through java Lab Department of M.C.A

Page 12: Java Record

HT.NO: 08F41F0040

class AddLinenumbers { public static void main(String args[]) { if(args.length<1) { System.out.println("File name not specified"); System.exit(0); } try { File f=new File(args[0]); FileReader fin=new FileReader(f); BufferedReader in= new BufferedReader(fin); String line=" "; int count=1; while((line=in.readLine())!=null) { System.out.println(count+":"+line); count++; } in.close(); } catch(IOException e) { System.out.println("Error opening file:"+e); } } }

/***********OUTPUT*****************

D:\gaja>javac AddLinenumbers.java

D:\gaja>java AddLinenumbers prime.java1:class prime2:{3:public static void main (String args[ ]);4:{5:int prime=0,num;6:num=Integer.parseInt(args[]);7:for(int i=2;i<=num-1;i++)8:{

Data Structures through java Lab Department of M.C.A

Page 13: Java Record

HT.NO: 08F41F0040

9:for(int j=2;j<30;j++)10:if(i!=j)11:{12:if(i%j==0)13:{14:prime=0;15:break;16:}17:else18:prime=1;19:}20:if(prime==1)21:System.out.println(i);22:}23:}24:}

*/

Program No:-10Program Name: Write a Java program that displays the number of characters, lines and words in a text file.

// Display no.of lines,characters and words in a text file

import java.lang.*;import java.io.*;import java.util.*;class WordCount{public static int words=0;public static int lines=0;public static int chars=0;public static void wc(InputStreamReader isr) throws IOException{

int c = 0;boolean lastWhite = true;String WhiteSpace = "\t\n\r";while((c=isr.read()) != -1){

Data Structures through java Lab Department of M.C.A

Page 14: Java Record

HT.NO: 08F41F0040

chars++;if(c=='\n'){

lines++;}int index = WhiteSpace.indexOf(c);if(index == -1){

if(lastWhite == true){

++words;}lastWhite = false;

}else

lastWhite = true;}if(chars != 0)

++lines;}

public static void main(String args[]){

FileReader fr;try

{InputStreamReader in = new

InputStreamReader(System.in);BufferedReader br = new BufferedReader(in);System.out.println("Enter the Filename: ");String fname = br.readLine();fr = new FileReader(fname);wc(fr);

}catch(IOException e)

{System.out.println("caunght Exception: " + e);

}System.out.println("Lines: " + lines + "\n Words: " + words +

"\n Chars: " + chars);}}

/********OUTPUT**********

D:\java>javac WordCount.java

D:\java>java WordCountEnter the Filename:totalmemory.txt

Data Structures through java Lab Department of M.C.A

Page 15: Java Record

HT.NO: 08F41F0040

Lines: 4 Words: 4 Chars: 119

*/

Program No:-11Program Name: Write a Java Program for creating multiple threads

a) Using Thread classb) Using Runnable interface.

// 11) a). Using Thread Class

import java.io.*;

class Thread2 extends Thread{public void run(){for(int i=11;i<20;i++) System.out.print(i+” “);}}class thread1{public static void main(String args[]){Thread2 t=new Thread2();t.start();for(int i=0;i<10;i++)System.out.print(i+” “);}}

/*********OUTPUT**********D:\dslab>javac thread1.java

D:\dslab>java thread1

Data Structures through java Lab Department of M.C.A

Page 16: Java Record

HT.NO: 08F41F0040

0 1 2 3 4 5 6 7 8 11 9 12 13 15 16 17 18 19

*/

// b) Using Runnable interface.

import java.io.*;

class thread1 implements Runnable{public void run(){for(int i=11;i<20;i++)System.out.print(i+” “);}}class thread{public static void main(String args[]){thread1 t1=new thread1();Thread r=new Thread(t1);r.start();for(int i=0;i<10;i++)System.out.print(i+” “);}}

/**********OUTPUT************

D:\dslab>javac thread.javaD:\dslab>java thread

11 0 1 2 3 4 5 6 7 8 9 12 13 14 15 16 17 18 19

*/

Data Structures through java Lab Department of M.C.A

Page 17: Java Record

HT.NO: 08F41F0040

Program No:-12Program Name: Write a Java Program that illustrates how run time polymorphism is achieved

class super1{int x;super1(int x){this.x=x;}void display(){System.out.println("class super1 - variable X= "+x);}}class sub extends super1{int y;sub(int x,int y){super(x);this.y=y;}void display(){System.out.println("class super1 - variable x= "+x);System.out.println("class sub - variable y= "+y);}}class runtime{public static void main(String args[]){sub s1=new sub(10,20);s1.display();}} /***********Output**********D:\dslab>javac runtime.javaD:\dslab>java runtime class super1 - variable x= 10 class sub - variable y= 20 */

Data Structures through java Lab Department of M.C.A

Page 18: Java Record

HT.NO: 08F41F0040

Program No:-13Program Name: Write a Java program that illustrates the folloiwng

a) Creation of simple packagaeb) Accessing a packagec) Implementing interface

Package structure Mypack(folder) | |--------mca(folder) | | | |-------a.java(interface) | |--------mba(folder) | | | |-------b.java(abstract class implementing interface a) | |--------c.java(class extending to class b)

// a.java

package mypack.mca;

public interface a{

public void print();public void sum(int a,int b);

}

// b.java

package mypack.mba;import mypack.mca.a;public abstract class b implements a{public void print(){ System.out.println("iam in abstract class B");}}

// c.java

package mypack;import mypack.mba.b;public class c extends b

Data Structures through java Lab Department of M.C.A

Page 19: Java Record

HT.NO: 08F41F0040

{public void print1(){ print(); System.out.println("iam in Class c");}

public void sum(int a, int b){

System.out.println("The sum of the numbers is :" + (a + b));

}public static void main(String args[]){c c1=new c();c1.print1();c1.sum(10, 20);} }

/*********OUTPUT************

D:\dslab\varun>javac mypack/c.java

D:\dslab\varun>java mypack.ciam in abstract class Biam in Class cThe sum of the numbers is :30

*/

Data Structures through java Lab Department of M.C.A

Page 20: Java Record

HT.NO: 08F41F0040

Program No:-14Program Name: Writa a Java program that illustrates the following

a) Handling predefined exceptionsb) Handling user defined exceptions

// a) Handling predefined exceptions

import java.io.*;class pd{public static void main(String args[]) throws ArithmeticException{int n=Integer.parseInt(args[0]);int a=Integer.parseInt(args[1]);pd d=new pd();d.div(n,a);}void div(int n,int a)throws ArithmeticException{System.out.println("division:"+(n/a));}}

/*********Output*********

D:\dslab>javac pd.javaD:\dslab>java pd 6 2 Division of number is : 3

1D:\dslab>java pd 6 0 Exception in thread "main" java.lang.ArithmeticException: / by zero at pd.div(pd.java:13) at pd.main(pd.java:8)*/

// b) Userdefined Exception

class user

Data Structures through java Lab Department of M.C.A

Page 21: Java Record

HT.NO: 08F41F0040

{public static void main(String args[]){int age;age=Integer.parseInt(args[0]);if(age<0){ try { throw new AgeNegative("Age should be +ve"); } catch(AgeNegative an) { an.printStackTrace(); }}else System.out.println("Age is "+age);}}class AgeNegative extends Exception{AgeNegative(String s){ super(s);} }

/**********Output***********

D:\dslab>javac user.javaD:\dslab>java user : 15 Age is 15D:\dslab>java user -15 AgeNegative: Age should be +ve at user.main(user.java:12)*/

Program No:-15Program Name: Write a Java program that use both recursive and non-recursive functions for implementing the following searching methods.a. Linear Search b. Binary Search

import java.io.*;

Data Structures through java Lab Department of M.C.A

Page 22: Java Record

HT.NO: 08F41F0040

public class search{ public static void main(String args[]) throws IOException { search s=new search(); int a[]; int ele,size,opt;

BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter the Size : "); size=Integer.parseInt(br.readLine()); a=new int[size];

System.out.println("Enter the elements in sorted order\n");

for(int i=0;i<size;i++) a[i]=Integer.parseInt(br.readLine()); do { System.out.print("Enter the number to search : "); ele=Integer.parseInt(br.readLine());

System.out.println("\n\tSearching techniques"); System.out.println("1. Linear Search 2. Binary Search"); System.out.print("Choose the searching technique : "); int ch=Integer.parseInt(br.readLine());

switch(ch) { case 1:s.LSearch(a,ele); break; case 2:s.BSearch(a,size,ele); break; default:System.out.println("Choose the Correct option"); }

System.out.print("\nDo you want to continue (0 - false & 1 – true): "); opt=Integer.parseInt(br.readLine()); }while(opt==1); }

public void LSearch(int[] a,int ele) {

Data Structures through java Lab Department of M.C.A

Page 23: Java Record

HT.NO: 08F41F0040

for(int i=0;i<=a.length-1;i++) if(a[i]==ele) System.out.println("\nEle. found at location "+(i+1)); }

public void BSearch(int[] a,int size,int ele) { int lb=0,ub=size;

while(lb<=ub) { int mid=(lb+ub)/2;

if(a[mid] == ele) System.out.println("Element is found at "+(mid+1));

if(a[mid]<ele) lb=mid+1; else ub=mid-1; } }}

/********OUTPUT*********

D:\mca_I_year>javac search.javaD:\mca_I_year>java searchEnter the Size : 8Enter the elements in sorted order1214282935386779Enter the number to search : 79

Searching techniques1. Linear Search 2. Binary SearchChoose the searching technique : 2Element is found at 8

Data Structures through java Lab Department of M.C.A

Page 24: Java Record

HT.NO: 08F41F0040

Do you want to continue (0 - false & 1 - true): 1Enter the number to search : 14

Searching techniques1. Linear Search 2. Binary SearchChoose the searching technique : 1Ele. found at location 2

Do you want to continue (0 - false & 1 - true): 0

*/

Program No:-16Program Name: Write a Java program to implement the following using arrays List ADT

import java.util.*;class Listmethods{ Scanner input = new Scanner (System.in); int n; int[] List = new int[10]; void Create() { int n,i; System.out.print("Enter LIST SIZE [== 10]: "); n = input.nextInt(); for(i=0;i<n;i++) { System.out.print("Enter Element "+i+" :"); List[i] = input.nextInt(); System.out.println("i= "+List[i]); }System.out.println(" The List has been Successfully Created: ");}void Display( ){ int i; System.out.println("\n The Created List is ...\n");

Data Structures through java Lab Department of M.C.A

Page 25: Java Record

HT.NO: 08F41F0040

for( i=0; i<List.length; i++) System.out.println(List[i]);}

void Reverse(){ int i; System.out.println("\n The Reverse List is ...\n"); for(i=List.length-1;i>=0;i--) System.out.println(List[i]);}

void Search(){ int i,si;System.out.print("Enter Element to Search: ");si = input.nextInt();for(i=0; i<List.length;i++) if(List[i] == si) { System.out.println("Search Element Found at Index: "+i); return; } System.out.println("Search Element Not Found");}void Delete(){ int i,si;System.out.print("Enter Element to DELETE: ");si = input.nextInt();for(i=0;i<List.length;i++)if(List[i] == si){ List[i] = -1; System.out.println("ELEMENT DELETED"); System.out.println("[-1 indicates as DELETED]"); return; }System.out.println("Search Element Not Found - can't Delete."); }}

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

Data Structures through java Lab Department of M.C.A

Page 26: Java Record

HT.NO: 08F41F0040

Listmethods s = new Listmethods(); Scanner input = new Scanner(System.in); int i = 1; int[] List = new int[10]; int choice; do { System.out.println("\n 1.CREATE \n 2.DISPLAY \n 3.REVERSE "); System.out.println("\n 4.SEARCH \n 5.DELETE \n 6.QUIT "); System.out.print("Enter your choice(1-6) : "); choice = input.nextInt(); switch(choice) { case 1: s.Create(); break; case 2: s.Display(); break; case 3: s.Reverse(); break; case 4: s.Search(); break; case 5: s.Delete(); break; case 6: System.exit(0); break; default: System.out.println("Invalid Choice. Try 1-6\n"); }}while(i<=choice);}}

/********OUTPUT**********

D:\JAVA>javac ListADT.java

D:\JAVA>java ListADT

1.CREATE 2.DISPLAY 3.REVERSE 4.SEARCH 5.DELETE 6.QUITEnter your choice(1-6) : 1Enter LIST SIZE [== 10]: 10Enter Element 0 :10i= 10Enter Element 1 :20i= 20Enter Element 2 :30i= 30Enter Element 3 :40i= 40Enter Element 4 :50

Data Structures through java Lab Department of M.C.A

Page 27: Java Record

HT.NO: 08F41F0040

i= 50Enter Element 5 :60i= 60Enter Element 6 :70i= 70Enter Element 7 :80i= 80Enter Element 8 :90i= 90Enter Element 9 :100i= 100 The List has been Successfully Created:

1.CREATE 2.DISPLAY 3.REVERSE 4.SEARCH 5.DELETE 6.QUITEnter your choice(1-6) : 2

The Created List is ...

102030405060708090100

1.CREATE 2.DISPLAY 3.REVERSE 4.SEARCH 5.DELETE 6.QUITEnter your choice(1-6) : 3

The Reverse List is ...

10090807060

Data Structures through java Lab Department of M.C.A

Page 28: Java Record

HT.NO: 08F41F0040

5040302010

1.CREATE 2.DISPLAY 3.REVERSE 4.SEARCH 5.DELETE 6.QUITEnter your choice(1-6) : 4Enter Element to Search: 50Search Element Found at Index: 4

1.CREATE 2.DISPLAY 3.REVERSE 4.SEARCH 5.DELETE 6.QUITEnter your choice(1-6) : 5Enter Element to DELETE: 50ELEMENT DELETED[-1 indicates as DELETED]

1.CREATE 2.DISPLAY 3.REVERSE 4.SEARCH 5.DELETE 6.QUITEnter your choice(1-6) : 2

The Created List is ...

10203040-160708090100 1.CREATE 2.DISPLAY

Data Structures through java Lab Department of M.C.A

Page 29: Java Record

HT.NO: 08F41F0040

3.REVERSE 4.SEARCH 5.DELETE 6.QUIT Enter your choice(1-6) : 6

*/

Data Structures through java Lab Department of M.C.A

Page 30: Java Record

HT.NO: 08F41F0040

Program No:-17Program Name: Write a Java program to implement the foloiwng using an array.

a) Stack ADTb) Queue ADT

// a) Stack ADT using array import java.util.*;class Stackmethods{ Scanner input = new Scanner (System.in); int top = -1; int data[ ] = new int[5]; void push() { if(top==4) System.out.print("Stack OverFlow"); else { System.out.print("Enter Data: "); top++; data[top] = input.nextInt(); }}void pop( ){ if(top==-1) System.out.println("Stack Underflow");else{ System.out.println("Poped element is: " + data[top]); top = top -1;}}

void display(){ if(top==-1) System.out.println("Stack Underflow"); else { for(i=top;i>=0;i--) { if(i==top) System.out.print("Top -> " + data[i]); else

Data Structures through java Lab Department of M.C.A

Page 31: Java Record

HT.NO: 08F41F0040

System.out.print(" " + data[i]); } } }} class StackADT{ public static void main(String args[]) { Stackmethods s = new Stackmethods(); Scanner input = new Scanner(System.in); int i = 1; int data[i] = new int[10]; System.out.println("\n 1.PUSH \n 2.POP \n 3.DISPLAY \n 4. EXIT \n "); System.out.println("\n 4.SEARCH \n 5.DELETE \n 6.QUIT "); int choice; do { System.out.println("Enter your Choice: " ); choice = input.nextInt(); switch(choice) { case 1: s.push(); break; case 2: s.pop(); break; case 3: s.display(); break; case 4: System.exit(0); break; default: System.out.println("Invalid Choice"); }}while(i<=choice);}}

/*******OUTPUT******

D:\JAVA>javac StackADT.java

D:\JAVA>java StackADT

1.PUSH 2.POP 3.DISPLAY 4. EXIT

Data Structures through java Lab Department of M.C.A

Page 32: Java Record

HT.NO: 08F41F0040

Enter your Choice: 1Enter Data: 10

Enter your Choice: 1Enter Data: 20

Enter your Choice: 1Enter Data: 30

Enter your Choice: 3Top -> 30 20 10

Enter your Choice: 2Poped element is: 30

Enter your Choice: 3Top -> 20 10

Enter your Choice: 4 */

// b) Queue ADT

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

class Queue{

BufferedReader br;

private int maxsize,front,rear,nitems;private int[] qarray;

public Queue(int n){

Data Structures through java Lab Department of M.C.A

Page 33: Java Record

HT.NO: 08F41F0040

maxsize=n;qarray=new int[maxsize];front=0;rear=-1;nitems=0;}

public void insert() throws IOException{if(isFull()!=true){int data;System.out.println("Enter element to insert : ");br=new BufferedReader(new InputStreamReader(System.in));data=Integer.parseInt(br.readLine());

if(rear==(maxsize-1)) rear=-1;qarray[++rear]=data;nitems++;System.out.println("New element is inserted\n");}elseSystem.out.println("Queue is full. can't perform Insertion.");}

public void delete(){if(isEmpty()!=true){front++;if(front==maxsize)front=0;nitems--;System.out.println("First element is deleted\n");}elseSystem.out.println("Queue is empty.");}

public boolean isEmpty(){return(nitems==0);}

public boolean isFull(){return(nitems==maxsize);}

Data Structures through java Lab Department of M.C.A

Page 34: Java Record

HT.NO: 08F41F0040

public void display(){if(isEmpty()!=true){System.out.println("Queue : ");for(int i=front;i<=rear;i++) System.out.println(qarray[i]);}elseSystem.out.println("Queue is empty.");}}

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

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

System.out.print("Enter the Queue size : ");int n=Integer.parseInt(br.readLine());

Queue q1=new Queue(n);

int i=1;int ch;

do{System.out.println("\nQUEUE");System.out.println("--------");System.out.println("1.Insert 2.Delete 3.Display 4.Quit");System.out.print("Enter the choice : ");ch=Integer.parseInt(br.readLine());

switch(ch){

case 1:q1.insert(); break;case 2:q1.delete(); break;case 3:q1.display(); break;case 4:System.exit(0);

Data Structures through java Lab Department of M.C.A

Page 35: Java Record

HT.NO: 08F41F0040

default:System.out.println("Invalid choice");}}while(1<=ch);}}

/***********OUTPUT**********

D:\mca_I_year>java qEnter the Queue size : 3

QUEUE--------1.Insert 2.Delete 3.Display 4.QuitEnter the choice : 1Enter element to insert :34New element is inserted

QUEUE--------1.Insert 2.Delete 3.Display 4.QuitEnter the choice : 1Enter element to insert :23New element is inserted

QUEUE--------1.Insert 2.Delete 3.Display 4.QuitEnter the choice : 1Enter element to insert :56New element is inserted

Data Structures through java Lab Department of M.C.A

Page 36: Java Record

HT.NO: 08F41F0040

QUEUE--------1.Insert 2.Delete 3.Display 4.QuitEnter the choice : 1Queue is full. can't perform Insertion.

QUEUE--------1.Insert 2.Delete 3.Display 4.QuitEnter the choice : 3Queue :342356

QUEUE--------1.Insert 2.Delete 3.Display 4.QuitEnter the choice : 2First element is deleted

QUEUE--------1.Insert 2.Delete 3.Display 4.QuitEnter the choice : 3Queue :2356

QUEUE--------1.Insert 2.Delete 3.Display 4.QuitEnter the choice : 4

*/

Data Structures through java Lab Department of M.C.A

Page 37: Java Record

HT.NO: 08F41F0040

Program No:-18Program Name: Write a Java program that reads a infix expression, converts the expression to postfix and postfix evaluation(use stack ADT)

a. Infix to Postfix conversion

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

class Intopost{

java.util.Stack<Character> s = new java.util.Stack<Character>();

public String topost(String infix){

infix = "(" + infix + ")";String postfix = "";

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

char ch, item;ch = infix.charAt(i);

if (isOperand(ch))postfix = postfix + ch;

if (ch == '(')s.push(ch);

if (isOperator(ch)){

item = s.pop();

if (isOperator(item)){

if (precedence(item) >= precedence(ch))

{s.push(item);s.push(ch);

}else{

Data Structures through java Lab Department of M.C.A

Page 38: Java Record

HT.NO: 08F41F0040

postfix = postfix + item;s.push(ch);

}}else{

s.push(item);s.push(ch);

}}

if (ch == ')'){

item = s.pop();while (item != '('){

postfix = postfix + item;item = s.pop();

}}

}return postfix;

}

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;

if (c == '+' || c == '-')rank = 2;

return rank;}

}

class Postfix {

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

Data Structures through java Lab Department of M.C.A

Page 39: Java Record

HT.NO: 08F41F0040

{BufferedReader br=new BufferedReader(new

InputStreamReader(System.in));

Intopost p=new Intopost();String s;

System.out.print("Enter the Infix expression : ");s=br.readLine();

System.out.println("Infix expression : " + s);

System.out.println("Postfix expression : "+p.topost(s));

}

}

/**********OUTPUT*********** D:\java\mca_I_year>java PostfixEnter the Infix expression : (A*(B+C)-D)Infix expression : (A*(B+C)-D)Postfix expression : ABC+*D-

D:\java\mca_I_year>java PostfixEnter the Infix expression : A*((B+C)-D)Infix expression : A*((B+C)-D)Postfix expression : ABC+D-* */

b. Postfix Evaluation

import java.io.*;

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

java.util.Stack<Integer> stk= new java.util.Stack<Integer>();

Data Structures through java Lab Department of M.C.A

Page 40: Java Record

HT.NO: 08F41F0040

char ch;

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));String p=br.readLine();

for(int i=0;i<p.length();i++){ch=p.charAt(i);

if(isDigit(ch))stk.push(new Integer(Character.digit(ch,10)));

if(isOperator(ch)){ int tmp1=stk.pop();int tmp2=stk.pop();int result=evaluate(tmp2,tmp1,ch);stk.push(result);}}System.out.println("Value of Postfix = " + stk.pop());}

static boolean isDigit(char c){return(c>='0' && c<='9');}

static boolean isOperator(char c){return(c=='+' || c=='-' || c=='*' || c=='/');}

static int evaluate(int a,int b,char op){int res=0;switch(op){ case '+': res=(a+b); break;case '-': res=(a-b); break;case '*': res=(a*b); break;case '/': res=(a/b); break;}

Data Structures through java Lab Department of M.C.A

Page 41: Java Record

HT.NO: 08F41F0040

return res;}}

/***********OUTPUT*********

D:\mca_I_year>javac Peval.java

D:\mca_I_year>java Peval2 3 4 + 5 * +Value of Postfix = 37

*/

Program No:-19Program Name: Write a java program that determines whether parenthetic symbols (), {} and <> are nested correctly in a string of characters (use stack ADT)

import java.io.*;

class Astack{private Object a[];private int top;

public Astack(int n){a=new Object[n];top=-1;}

public void push(Object item){if(top==a.length-1)

Data Structures through java Lab Department of M.C.A

Page 42: Java Record

HT.NO: 08F41F0040

{System.out.println("Stack is full");return;}top++;a[top]=item;}

public Object pop(){if(isEmpty()){System.out.println("stack is empty");return null;}Object item=a[top];top--;return item;}

public Object peek(){if(isEmpty()) return null;return a[top];}

public boolean isEmpty(){return(top==-1);}

}

class Astackdemo{public static void main(String args[]) throws IOException{Astack a=new Astack(6);Object item;

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

String s=br.readLine();

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

Data Structures through java Lab Department of M.C.A

Page 43: Java Record

HT.NO: 08F41F0040

{

if(s.charAt(i)=='(' || s.charAt(i)=='[' || s.charAt(i)=='{' || s.charAt(i)=='<') a.push(s.charAt(i));

char c=(Character)a.peek();

if(s.charAt(i)==')') { if(c=='(') a.pop(); else { System.out.println("Not Correctly Nested Parenthesis"); System.exit(0); } }

else if(s.charAt(i)==']') { if(c=='[') a.pop(); else { System.out.println("Not Correctly Nested Parenthesis"); System.exit(0); } }

else if(s.charAt(i)=='}') { if(c=='{') a.pop(); else { System.out.println("Not Correctly Nested Parenthesis"); System.exit(0); } } else if(s.charAt(i)=='>') { if(c=='<') a.pop(); else { System.out.println("Not Correctly Nested Parenthesis"); System.exit(0);

Data Structures through java Lab Department of M.C.A

Page 44: Java Record

HT.NO: 08F41F0040

} } }if(a.isEmpty())System.out.println("Correctly Nested Parenthesis");elseSystem.out.println("Not Correctly Nested Parenthesis");

}}/***********OUTPUT************

D:\mca_I_year>javac Astackdemo.java

D:\mca_I_year>java Astackdemo(hello.ho[w are]Not Correctly Nested Parenthesis

D:\mca_I_year>java Astackdemo(hello.ho[w are])Correctly Nested Parenthesis

D:\mca_I_year>D:\mca_I_year>java Astackdemo(hello.ho[w are)Not Correctly Nested Parenthesis

*/

Data Structures through java Lab Department of M.C.A

Page 45: Java Record

HT.NO: 08F41F0040

Program No:-20Program Name: Write a java program that uses queue to test whether the given string is palindrome.

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

class Queue{

BufferedReader br;

private int maxsize,front,rear,nitems;private char[] qarray;

public Queue(int n){maxsize=n;qarray=new char[maxsize];front=0;rear=-1;nitems=0;}

public void insert() throws IOException{if(isFull()!=true){char data;System.out.println("Enter element to insert : ");br=new BufferedReader(new InputStreamReader(System.in));data=(char)br.read();

if(rear==(maxsize-1)) rear=-1;qarray[++rear]=data;nitems++;System.out.println("New element is inserted\n");}elseSystem.out.println("Queue is full. can't perform Insertion.");}public void delete(){if(isEmpty()!=true)

Data Structures through java Lab Department of M.C.A

Page 46: Java Record

HT.NO: 08F41F0040

{front++;if(front==maxsize)front=0;nitems--;System.out.println("First element is deleted\n");}elseSystem.out.println("Queue is empty.");}

public boolean isEmpty(){return(nitems==0);}

public void isPal(){ int i,j,count=0,n=nitems; for(i=front,j=rear;i<=n/2 && j>=n/2;i++,j--) if(qarray[i]==qarray[j]) count++; if((n%2)!=0) count--; if(count==(n/2)) System.out.println("palindrome"); else System.out.println("Not a palindrome"); }

public boolean isFull(){ return(nitems==maxsize);}

public void display(){if(isEmpty()!=true){System.out.println("Queue : ");for(int i=front;i<=rear;i++) System.out.println(qarray[i]);}else

Data Structures through java Lab Department of M.C.A

Page 47: Java Record

HT.NO: 08F41F0040

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

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

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

System.out.print("Enter the Queue size : ");int n=Integer.parseInt(br.readLine());

Queue q1=new Queue(n);

int i=1;int ch;

do{System.out.println("\nQUEUE");System.out.println("--------");System.out.println("1.Insert 2.Delete 3.Display 4.Quit 5. Palindrome");System.out.print("Enter the choice : ");ch=Integer.parseInt(br.readLine());

switch(ch){

case 1:q1.insert(); break;case 2:q1.delete(); break;case 3:q1.display(); break;case 4:System.exit(0); break;case 5:q1.isPal(); break; default:System.out.println("Invalid choice");}}while(1<=ch);}}

Data Structures through java Lab Department of M.C.A

Page 48: Java Record

HT.NO: 08F41F0040

/***********OUTPUT**********

D:\mca_I_year>java quEnter the Queue size : 5

QUEUE--------1.Insert 2.Delete 3.Display 4.Quit 5. PalindromeEnter the choice : 1Enter element to insert :mNew element is inserted

QUEUE--------1.Insert 2.Delete 3.Display 4.Quit 5. PalindromeEnter the choice : 1Enter element to insert :aNew element is inserted

QUEUE--------1.Insert 2.Delete 3.Display 4.Quit 5. PalindromeEnter the choice : 1Enter element to insert :dNew element is inserted

QUEUE--------1.Insert 2.Delete 3.Display 4.Quit 5. PalindromeEnter the choice : 1Enter element to insert :aNew element is inserted

QUEUE--------1.Insert 2.Delete 3.Display 4.Quit 5. PalindromeEnter the choice : 1Enter element to insert :mNew element is inserted

Data Structures through java Lab Department of M.C.A

Page 49: Java Record

HT.NO: 08F41F0040

QUEUE--------1.Insert 2.Delete 3.Display 4.Quit 5. PalindromeEnter the choice : 3Queue :madam

QUEUE--------1.Insert 2.Delete 3.Display 4.Quit 5. PalindromeEnter the choice : 5palindrome

QUEUE--------1.Insert 2.Delete 3.Display 4.Quit 5. PalindromeEnter the choice : 2First element is deleted

QUEUE--------1.Insert 2.Delete 3.Display 4.Quit 5. PalindromeEnter the choice : 3Queue :adam

QUEUE--------1.Insert 2.Delete 3.Display 4.Quit 5. PalindromeEnter the choice : 5Not a palindrome

QUEUE--------1.Insert 2.Delete 3.Display 4.Quit 5. PalindromeEnter the choice : 4

*/

Data Structures through java Lab Department of M.C.A

Page 50: Java Record

HT.NO: 08F41F0040

Program No:-21Program Name: Write a java program to implement Stack ADT using a singly linked list

import java.io.*;

class Node{int data;Node next;Node(int d){data=d;}}

class Lstack{Node top;Node p;

public void push(int item){p=new Node(item);p.next=top;top=p;}

public Node pop(){

Data Structures through java Lab Department of M.C.A

Page 51: Java Record

HT.NO: 08F41F0040

if(isEmpty()){System.out.println("Stack is empty");return null;}Node tmp=top;top=tmp.next;return tmp;}

public Node peek(){if(isEmpty()){ System.out.println("Stack is empty"); return null;}return top;}

public void display(){p=top;System.out.println("Contents of stack");while(p!=null){System.out.print(p.data+" ");p=p.next;}}

public boolean isEmpty(){return(top==null);}

} // End of class

class Linkstack{

public static void main(String args[]) throws IOException{ Lstack ls=new Lstack(); Node item; int ch,n,ch1;

Data Structures through java Lab Department of M.C.A

Page 52: Java Record

HT.NO: 08F41F0040

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

do { System.out.println("\nStack process\n"); System.out.println("1.Push 2.Pop 3.Peek 4.Display 5.Exit"); System.out.print("Enter your choice : "); ch=Integer.parseInt(br.readLine()); switch(ch) { case 1:System.out.print("\nEnter element to push into stack : "); n=Integer.parseInt(br.readLine()); ls.push(n); break; case 2:ls.pop(); break; case 3: ls.peek(); break; case 4:ls.display(); break; case 5:System.exit(0); }

System.out.print("\nDo you want to continue (1-Yes,0-No): "); ch1=Integer.parseInt(br.readLine()); }while(ch1==1); }}

/***********OUTPUT********

D:\mca_I_year>javac Linkstack.java

D:\mca_I_year>java Linkstack

Stack process

1.Push 2.Pop 3.Peek 4.Display 5.ExitEnter your choice : 1

Enter element to push into stack : 12

Do you want to continue (1-Yes,0-No): 1

Stack process

1.Push 2.Pop 3.Peek 4.Display 5.Exit

Data Structures through java Lab Department of M.C.A

Page 53: Java Record

HT.NO: 08F41F0040

Enter your choice : 1

Enter element to push into stack : 23

Do you want to continue (1-Yes,0-No): 1

Stack process

1.Push 2.Pop 3.Peek 4.Display 5.ExitEnter your choice : 1

Enter element to push into stack : 34

Do you want to continue (1-Yes,0-No): 1

Stack process

1.Push 2.Pop 3.Peek 4.Display 5.ExitEnter your choice : 4Contents of stack34 23 12Do you want to continue (1-Yes,0-No): 1

Stack process

1.Push 2.Pop 3.Peek 4.Display 5.ExitEnter your choice : 2

Do you want to continue (1-Yes,0-No): 1

Stack process

1.Push 2.Pop 3.Peek 4.Display 5.ExitEnter your choice : 4Contents of stack23 12Do you want to continue (1-Yes,0-No): 5

*/

Program No:-22Program Name: Write a Java program to implement the dequeue (double ended queue) ADT using Singly Linked List

Data Structures through java Lab Department of M.C.A

Page 54: Java Record

HT.NO: 08F41F0040

class LinkedDeque{

public class DequeNode{

DequeNode prev;Object data;DequeNode next;

DequeNode( Object item) // constructor{

data = item;}

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

Data Structures through java Lab Department of M.C.A

Page 55: Java Record

HT.NO: 08F41F0040

}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 = first.data; first = first.next; first.prev = null; count--; return item;

}}

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: [ ");

Data Structures through java Lab Department of M.C.A

Page 56: Java Record

HT.NO: 08F41F0040

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();dq.addFirst('A');dq.addFirst('B');

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

}}

/********OUTPUT*********** D:\java>javac LinkedDequeDemo.java

D:\java>java LinkedDequeDemoDeque: [ BA]getFirst():BgetLast():EDeque: [ BADE]removeFirst():BremoveLast():ADeque: [ DE]size():2

Data Structures through java Lab Department of M.C.A

Page 57: Java Record

HT.NO: 08F41F0040

*/

Program No:-23Program Name: Write a java program to implement priority queue ADT.

import java.util.*;class PQueue{ Scanner input = new Scanner (System.in); private int maxsize; private int[] quearray; private int nitems;

public PQueue(){ maxsize = 5; quearray = new int[maxsize]; nitems = 0;}public void insert(){ if(isFull() != true){ int data,temp;System.out.print("Enter Element to Insert: ");data = input.nextInt();quearray[nitems++] = data;for(int i=nitems-1; i>=1;i--) for(int j=0;j<i;j++)

Data Structures through java Lab Department of M.C.A

Page 58: Java Record

HT.NO: 08F41F0040

if(quearray[j] > quearray[j+1]) { temp = quearray[j]; quearray[j] = quearray[j+1]; quearray[j+1] = temp;}System.out.println("New Element INSERTED. \n");}else System.out.println("QUEUE is Full. can't perform INSERT ");}public void delete(){ if(isEmpty() != true){ nitems--; System.out.println("First Element DELETED"); }

elseSystem.out.println("Queue is Empty. can't perform DELETE");}public boolean isEmpty(){ return (nitems == 0);}public boolean isFull(){ return(nitems == maxsize);} public void display(){ if(isEmpty() != true){ System.out.println("THE PRIORITY QUEUE IS :");for(int i=0;i<nitems; i++) System.out.println(quearray[i]);}elseSystem.out.println("Queue is Empty. can't perform TRAVERSE");}}class pq{ public static void main(String[] args){ PQueue tpq = new PQueue();Scanner input = new Scanner(System.in);int i =1;

Data Structures through java Lab Department of M.C.A

Page 59: Java Record

HT.NO: 08F41F0040

int choice;do{ System.out.println("\n PRIORITY QUEUE "); System.out.println("------------------------------------"); System.out.println(" 1.INSERT \n 2.DELETE \n 3.DISPLAY ");System.out.println("4.Quit");System.out.print("Enter your choice (1-4): ");choice = input.nextInt();switch(choice){ case 1: tpq.insert(); break; case 2:tpq.delete(); break; case 3:tpq.display();break;case 4:System.exit(0);break;default: System.out.println("Invalid choice. Try 1-4 \n");}}while(i<=choice);}}

/*****OUTPUT******

D:\JAVA>javac pq.java

D:\JAVA>java pq

PRIORITY QUEUE------------------------------------ 1.INSERT 2.DELETE 3.DISPLAY4.QuitEnter your choice (1-4): 1Enter Element to Insert: 5New Element INSERTED.

PRIORITY QUEUE------------------------------------ 1.INSERT 2.DELETE 3.DISPLAY4.QuitEnter your choice (1-4): 1Enter Element to Insert: 20New Element INSERTED.

Data Structures through java Lab Department of M.C.A

Page 60: Java Record

HT.NO: 08F41F0040

PRIORITY QUEUE------------------------------------ 1.INSERT 2.DELETE 3.DISPLAY4.QuitEnter your choice (1-4): 1Enter Element to Insert: 6New Element INSERTED. PRIORITY QUEUE------------------------------------ 1.INSERT 2.DELETE 3.DISPLAY4.QuitEnter your choice (1-4): 3THE PRIORITY QUEUE IS :5620

PRIORITY QUEUE------------------------------------ 1.INSERT 2.DELETE 3.DISPLAY4.QuitEnter your choice (1-4): 2First Element DELETED

PRIORITY QUEUE------------------------------------ 1.INSERT 2.DELETE 3.DISPLAY4.QuitEnter your choice (1-4): 3THE PRIORITY QUEUE IS :56 PRIORITY QUEUE------------------------------------ 1.INSERT 2.DELETE 3.DISPLAY4.QuitEnter your choice (1-4): 4 Program No:-24

Data Structures through java Lab Department of M.C.A

Page 61: Java Record

HT.NO: 08F41F0040

Program Name: Write a Java program to perform the following operations:

a) Insert an element into a binary search tree.b) Delete an element from a binary search tree.c) Search for a key element in a binary search tree.

import java.io.*;

class BSTNode{

int data;BSTNode left;BSTNode right;

BSTNode(int d){

data = d;}

}

class BST{

public BSTNode insertTree(BSTNode p, int key){

if (p == null)p = new BSTNode(key);

else if (key < p.data)p.left = insertTree(p.left, key);

elsep.right = insertTree(p.right, key);

return p;}

public BSTNode search(BSTNode root, int key){

BSTNode p = root;while (p != null){

if (key == p.data)return p;

else if (key < p.data)p = p.left;

elsep = p.right;

}return null;

}

Data Structures through java Lab Department of M.C.A

Page 62: Java Record

HT.NO: 08F41F0040

public BSTNode delTree(BSTNode root, int key){

BSTNode p;BSTNode parent = root;BSTNode inorderSucc;

if (root == null){

System.out.println("Tree is empty");return null;

}

p = root;

while (p != null && p.data != key){

parent = p;if (key < p.data)

p = p.left;else

p = p.right;}

if (p == null){

System.out.println("TNode not found : " + key);return null;

}

if (p.left != null && p.right != null){

parent = p;inorderSucc = p.right;

while (inorderSucc.left != null){

parent = inorderSucc;inorderSucc = inorderSucc.left;

}p.data = inorderSucc.data;p = inorderSucc;

}

if (p.left == null && p.right == null){

if (parent.left == p)parent.left = null;

elseparent.right = null;

Data Structures through java Lab Department of M.C.A

Page 63: Java Record

HT.NO: 08F41F0040

}

if (p.left == null && p.right != null){

if (parent.left == p)parent.left = p.right;

elseparent.right = p.right;

}

if (p.left != null && p.right == null){

if (parent.left == p)parent.left = p.left;

elseparent.right = p.left;

}

return root;}

public void preorder(BSTNode p){

if (p != null){

System.out.print(p.data + " ");preorder(p.left);preorder(p.right);

}}

}

class BinarySearchTree{

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

int barr[];

BST b = new BST();BSTNode root = null;

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

System.out.print("Enter the size of the tree : ");int n = Integer.parseInt(br.readLine());

barr = new int[n];

Data Structures through java Lab Department of M.C.A

Page 64: Java Record

HT.NO: 08F41F0040

for(int i=0;i<n;i++)barr[i] = Integer.parseInt(br.readLine());

for (int i = 0; i < n; i++)root = b.insertTree(root, barr[i]);

System.out.println("Preorder of tree : ");b.preorder(root);

System.out.print("\nEnter the element to search : ");n = Integer.parseInt(br.readLine());

BSTNode item = b.search(root, n);if (item != null)

System.out.println("\n Searching item "+ item.data +" found." );

elseSystem.out.println("\n Item not found");

System.out.print("\nEnter the node element to delete : ");

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

b.delTree(root, n);System.out.println("\nAfter deleting the node \

nPreorder of tree : ");b.preorder(root);

}}

/***********OUTPUT*********** D:\java\mca_I_year>java BinarySearchTreeEnter the size of the tree : 81245788956231535Preorder of tree :12 45 23 15 35 78 56 89Enter the element to search : 15

Data Structures through java Lab Department of M.C.A

Page 65: Java Record

HT.NO: 08F41F0040

Searching item 15 found. Enter the node element to delete : 15

After deleting the nodePreorder of tree :12 45 23 35 78 56 89 D:\java\mca_I_year>java BinarySearchTreeEnter the size of the tree : 81245788956231535Preorder of tree :12 45 23 15 35 78 56 89Enter the element to search : 91

Item not found

Enter the node element to delete : 98TNode not found : 98

After deleting the nodePreorder of tree :12 45 23 15 35 78 56 89 */

Data Structures through java Lab Department of M.C.A

Page 66: Java Record

HT.NO: 08F41F0040

Program No:-25Program Name: Write a Java program that use recursive and non – recursive functions to traverse the given binary tree in

a) Preorderb) Inorder andc) Postorder

class Node{ Object data;Node left;Node right;

Node(Object d) { data=d;}}

class BinaryTree{ Object tree[]; int maxsize; java.util.LinkedList<Node> que=new java.util.LinkedList<Node>();

BinaryTree(Object a[],int n) { maxsize=n;tree=new Object[maxsize];

for(int i=0;i<maxsize;i++) tree[i]=a[i];}

public Node buildTree(int index){ Node p; 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;}

Data Structures through java Lab Department of M.C.A

Page 67: Java Record

HT.NO: 08F41F0040

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+" "); 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+" ");}}}

public class BinaryTreeTraversal {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,19);Node root=t.buildTree(0);System.out.print("\nInorder : ");t.inorder(root);

System.out.print("\nPreorder : ");t.preorder(root);

System.out.print("\npostorder : ");t.postorder(root);

Data Structures through java Lab Department of M.C.A

Page 68: Java Record

HT.NO: 08F41F0040

}}

/*************OUTPUT ********

D:\java>javac BinaryTreeTraversal.java

D:\java>java BinaryTreeTraversal

Inorder : A B C D E F G HPreorder : E C A B D G F Hpostorder : B A D C F H G E */

Data Structures through java Lab Department of M.C.A

Page 69: Java Record

HT.NO: 08F41F0040

Program No:-26Program Name: Write Java program for the implementation of bfs and dfs for a given graph.

a. Breadth-First Search

class Queue{private final int SIZE = 20;private int[] queArray;private int front;private int rear;public Queue() // constructor{queArray = new int[SIZE];front = 0;rear = -1;}public void insert(int j) // put item at rear of queue{if(rear == SIZE-1)rear = -1;queArray[++rear] = j;}public int remove() // take item from front of queue{int temp = queArray[front++];if(front == SIZE)front = 0;return temp;}public boolean isEmpty() // true if queue is empty{return ( rear+1==front || (front+SIZE-1==rear) );}} // end class Queue

class Vertex{public char label; // label (e.g. 'A')public boolean wasVisited;public Vertex(char lab) // constructor{label = lab;wasVisited = false;}} // end class Vertex

Data Structures through java Lab Department of M.C.A

Page 70: Java Record

HT.NO: 08F41F0040

class Graph{private final int MAX_VERTS = 20;private Vertex vertexList[]; // list of verticesprivate int adjMat[][]; // adjacency matrixprivate int nVerts; // current number of verticesprivate Queue theQueue;

public Graph() // constructor{vertexList = new Vertex[MAX_VERTS];

// adjacency matrixadjMat = new int[MAX_VERTS][MAX_VERTS];nVerts = 0;for(int j=0; j<MAX_VERTS; j++) // set adjacencyfor(int k=0; k<MAX_VERTS; k++) // matrix to 0adjMat[j][k] = 0;theQueue = new Queue();} // end constructorpublic void addVertex(char lab){vertexList[nVerts++] = new Vertex(lab);}public void addEdge(int start, int end){adjMat[start][end] = 1;adjMat[end][start] = 1;}

public void displayVertex(int v){System.out.print(vertexList[v].label);}

public void bfs() // breadth-first search{ // begin at vertex 0vertexList[0].wasVisited = true; // mark itdisplayVertex(0); // display ittheQueue.insert(0); // insert at tailint v2;while( !theQueue.isEmpty() ) // until queue empty,{int v1 = theQueue.remove(); // remove vertex at head

// until it has no unvisited neighborswhile( (v2=getAdjUnvisitedVertex(v1)) != -1 ){vertexList[v2].wasVisited = true; // mark it

Data Structures through java Lab Department of M.C.A

Page 71: Java Record

HT.NO: 08F41F0040

displayVertex(v2); // display ittheQueue.insert(v2); // insert it} // end while} // end while(queue not empty)

// queue is empty, so we're donefor(int j=0; j<nVerts; j++) // reset flagsvertexList[j].wasVisited = false;} // end bfs()

public int getAdjUnvisitedVertex(int v){for(int j=0; j<nVerts; j++) if(adjMat[v][j]==1 && vertexList[j].wasVisited==false) return j;return -1;} // end getAdjUnvisitedVert()}

class BFSApp{public static void main(String[] args){Graph theGraph = new Graph();theGraph.addVertex('A'); // 0 (start for dfs)theGraph.addVertex('B'); // 1theGraph.addVertex('C'); // 2theGraph.addVertex('D'); // 3theGraph.addVertex('E'); // 4theGraph.addEdge(0, 1); // ABtheGraph.addEdge(1, 2); // BCtheGraph.addEdge(0, 3); // ADtheGraph.addEdge(3, 4); // DESystem.out.print("Visits: ");theGraph.bfs(); // breadth-first searchSystem.out.println();} // end main()} // end class BFSApp

/********OUTPUT*********** D:\java\mca_I_year\bfs>javac BFSApp.java D:\java\mca_I_year\bfs>java BFSApp Visits: ABDCE */

Data Structures through java Lab Department of M.C.A

Page 72: Java Record

HT.NO: 08F41F0040

b. Depth First Search

class StackX{private final int SIZE = 20;private int[] st;private int top;public StackX() // constructor{st = new int[SIZE]; // make arraytop = -1;}public void push(int j) // put item on stack{ st[++top] = j; }public int pop() // take item off stack{ return st[top--]; }public int peek() // peek at top of stack{ return st[top]; }public boolean isEmpty() // true if nothing on stack{ return (top == -1); }} // end class StackX

class Vertex{public char label; // label (e.g. 'A')public boolean wasVisited;public Vertex(char lab) // constructor{label = lab;wasVisited = false;}} // end class Vertex

class Graph{private final int MAX_VERTS = 20;private Vertex vertexList[]; // list of verticesprivate int adjMat[][]; // adjacency matrixprivate int nVerts; // current number of verticesprivate StackX theStack;public Graph() // constructor{vertexList = new Vertex[MAX_VERTS];// adjacency matrixadjMat = new int[MAX_VERTS][MAX_VERTS];nVerts = 0;for(int j=0; j<MAX_VERTS; j++) // set adjacencyfor(int k=0; k<MAX_VERTS; k++) // matrix to 0adjMat[j][k] = 0;

Data Structures through java Lab Department of M.C.A

Page 73: Java Record

HT.NO: 08F41F0040

theStack = new StackX();} // end constructor

public void addVertex(char lab){vertexList[nVerts++] = new Vertex(lab);}

public void addEdge(int start, int end){adjMat[start][end] = 1;adjMat[end][start] = 1;}

public void displayVertex(int v){System.out.print(vertexList[v].label);}

public void dfs() // depth-first search{ // begin at vertex 0vertexList[0].wasVisited = true; // mark itdisplayVertex(0); // display ittheStack.push(0); // push itwhile( !theStack.isEmpty() ) // until stack empty,{// get an unvisited vertex adjacent to stack topint v = getAdjUnvisitedVertex( theStack.peek() );if(v == -1) // if no such vertex,theStack.pop();else // if it exists,{vertexList[v].wasVisited = true; // mark itdisplayVertex(v); // display ittheStack.push(v); // push it}} // end while// stack is empty, so we're donefor(int j=0; j<nVerts; j++) // reset flagsvertexList[j].wasVisited = false;} // end dfs// returns an unvisited vertex adj

public int getAdjUnvisitedVertex(int v){for(int j=0; j<nVerts; j++)if(adjMat[v][j]==1 && vertexList[j].wasVisited==false)return j;return -1;

Data Structures through java Lab Department of M.C.A

Page 74: Java Record

HT.NO: 08F41F0040

} // end getAdjUnvisitedVert()} // end class Graph

class DFSApp{public static void main(String[] args){Graph theGraph = new Graph();theGraph.addVertex('A'); // 0 (start for dfs)theGraph.addVertex('B'); // 1theGraph.addVertex('C'); // 2theGraph.addVertex('D'); // 3theGraph.addVertex('E'); // 4theGraph.addEdge(0, 1); // ABtheGraph.addEdge(1, 2); // BCtheGraph.addEdge(0, 3); // ADtheGraph.addEdge(3, 4); // DESystem.out.print("Visits: ");theGraph.dfs(); // depth-first searchSystem.out.println();} // end main()} // end class DFSApp

/*************OUTPUT************ D:\java\mca_I_year\dfs>javac DFSApp.java

D:\java\mca_I_year\dfs>java DFSApp Visits: ABCDE */

Data Structures through java Lab Department of M.C.A

Page 75: Java Record

HT.NO: 08F41F0040

Program No:-27Program Name: A Java program for implementing KMP pattern matching algorithm.

Note : // Define a command line test: java KMP <text> <pattern>

public class KMP{

public static void main(String[] args) {String txt = args[0], pat = args[1];System.out.printf("Searching for ’%s’ in text of length %d\n",pat, txt.length());int result = match(txt, pat);if (result < 0)System.out.println("No match.");elseSystem.out.println("Found first match at position= " + result);}static int match(String text, String pattern){int n = text.length();int m = pattern.length();int[] fail = failFunction(pattern);int i = 0, j = 0; // index in text, index in patternwhile (i < n) {if (pattern.charAt(j) == text.charAt(i)) {// Our match extends to length j+1if (j == m-1) return i-m+1; // found full matchi++; j++;} else if (j > 0) {j = fail[j - 1]; // try again for a shorter match} else {i++; // no match here at all}}return -1; // no match}// Compute the failure function for this pattern.static int[] failFunction(String pattern) {int[] fail = new int[pattern.length()];fail[0] = 0;int m = pattern.length();int i = 1, j = 0; // index in pattern(+1), index in patternwhile (i < m) {if (pattern.charAt(j) == pattern.charAt(i)) {fail[i] = j+1; // Our match extends to length j+1

Data Structures through java Lab Department of M.C.A

Page 76: Java Record

HT.NO: 08F41F0040

i++; j++;} else if (j > 0) {j = fail[j - 1]; // try again for a shorter match} else {fail[i] = 0; // no match here at alli++;}}return fail;}}/****************OUTPUT***********

D:\mca_I_year>javac KMP.java

D:\mca_I_year>java KMP hello,how heSearching for ÆheÆ in text of length 9Found first match at shift=0

D:\mca_I_year>java KMP hello,how hSearching for ÆhÆ in text of length 9Found first match at shift=0D:\mca_I_year>java KMP hello,how lSearching for ÆlÆ in text of length 9Found first match at shift=2D:\mca_I_year>java KMP hello,how xSearching for ÆxÆ in text of length 9No match.*/

Data Structures through java Lab Department of M.C.A

Page 77: Java Record

HT.NO: 08F41F0040

Program No:-28Program Name: Write a Java program that displays node values in a level order traversal for a binary tree.

class Node{ Object data;Node left;Node right;

Node(Object d) { data=d;}}

class BinaryTree{

Object tree[];int maxsize;

java.util.LinkedList<Node> que = new java.util.LinkedList<Node>();

BinaryTree(Object a[], int n){

maxsize = n;tree = new Object[maxsize];

for (int i = 0; i < maxsize; i++)tree[i] = a[i];

}

public Node buildTree(int index){

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

}public void levelorder(Node p)

Data Structures through java Lab Department of M.C.A

Page 78: Java Record

HT.NO: 08F41F0040

{ que.addLast(p); while( !que.isEmpty() ) { p = que. removeFirst(); System.out.print(p.data + " "); if(p.left != null) que.addLast(p.left); if(p.right != null) que.addLast(p.right); }}

}public 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,19);Node root=t.buildTree(0);System.out.print("\nLevel order : ");t.levelorder(root);

}}

/********OUTPUT*********

D:\java>javac BinaryTreeDemo.java

D:\java>java BinaryTreeDemo

Level order : E C G A D F H B

Data Structures through java Lab Department of M.C.A