0% found this document useful (0 votes)
169 views78 pages

Java Record

The document contains 9 Java programs with descriptions and sample outputs: 1. A program that reads coefficients of a quadratic equation and prints the real solutions. 2. Programs that calculate the nth Fibonacci number using recursive and non-recursive functions. 3. A program that takes a number from the user and prints all prime numbers up to that number. 4. A program that checks if a given string is a palindrome. 5. A program that sorts an array of names in ascending order. 6. A program that multiplies two matrices. 7. A program that reads integers from a line and calculates their sum using StringTokenizer. 8. A program that

Uploaded by

J Nikle Reddy
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
169 views78 pages

Java Record

The document contains 9 Java programs with descriptions and sample outputs: 1. A program that reads coefficients of a quadratic equation and prints the real solutions. 2. Programs that calculate the nth Fibonacci number using recursive and non-recursive functions. 3. A program that takes a number from the user and prints all prime numbers up to that number. 4. A program that checks if a given string is a palindrome. 5. A program that sorts an array of names in ascending order. 6. A program that multiplies two matrices. 7. A program that reads integers from a line and calculates their sum using StringTokenizer. 8. A program that

Uploaded by

J Nikle Reddy
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 78

HT.

NO: 08F41F0040 Program No:-1 Program 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

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.java D:\dslab\varun>java fib1 Enter the series range : 20

Data Structures through java Lab

Department of M.C.A

HT.NO: 08F41F0040 Enter the sequence position : 9 The fibonacci number at position 9 is 34 D:\dslab\varun>java fib1 Enter the series range : 30 Enter the sequence position : 7 The 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

HT.NO: 08F41F0040 { int temp=prev; prev=cur; cur=cur+temp; return cur; } } /**********OUTPUT********** D:\dslab>javac fib.java D:\dslab>java fib Series Range 10 Enter the sequenc position 5 the fibonaci number of 6 is 8. D:\dslab>java fib Series Range 10 Enter the sequenc position 9 not in fib range */

Program No:-3 Program 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

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 5 D:\dslab>java prime 15 The prime number series is 2 3 5 7 11 13 */

Program No:-4 Program 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"); else System.out.println(Str1+ " is not palindrome");

Data Structures through java Lab

Department of M.C.A

HT.NO: 08F41F0040 } } /********Output************ D:\dslab>javac palindrome.java D:\dslab>java palindrome Enter the string : MALAYALAM MALAYALAM is palindrome D:\dslab>java palindrome Enter the string: SREENATH SREENATH is not palindrome */

Program No:-5 Program 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

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.java D:\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

HT.NO: 08F41F0040

Program No:-6 Program 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

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.java D:\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

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.java D:\dslab>java tokens : 6 8 10 Sum of numbers is : 24 */

Program No:8 Program 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

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.java D:\dslab>java Filedemo fib.java filename :fib.java pathname:fib.java exist Writable readable filesize:810Bytes D:\dslab>java Filedemo fibretw.java filename :fibretw.java pathname:fibretw.java Does not exist is not writable is not readable filesize:0Bytes */ Program No:-9 Program 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.*; class AddLinenumbers

Data Structures through java Lab

Department of M.C.A

HT.NO: 08F41F0040 { 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.java 1:class prime 2:{ 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:{ 9:for(int j=2;j<30;j++)

Data Structures through java Lab

Department of M.C.A

HT.NO: 08F41F0040 10:if(i!=j) 11:{ 12:if(i%j==0) 13:{ 14:prime=0; 15:break; 16:} 17:else 18:prime=1; 19:} 20:if(prime==1) 21:System.out.println(i); 22:} 23:} 24:} */

Program No:-10 Program 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) { chars++;

Data Structures through java Lab

Department of M.C.A

HT.NO: 08F41F0040 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 WordCount Enter the Filename: totalmemory.txt Lines: 4

Data Structures through java Lab

Department of M.C.A

HT.NO: 08F41F0040 Words: 4 Chars: 119 */

Program No:-11 Program Name: Write a Java Program for creating multiple threads a) Using Thread class b) 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 0 1 2 3 4 5 6 7 8 11 9 12 13 15 16 17 18 19

Data Structures through java Lab

Department of M.C.A

HT.NO: 08F41F0040

*/

// 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.java D:\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

HT.NO: 08F41F0040

Program No:-12 Program 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.java D:\dslab>java runtime class super1 - variable x= 10 class sub variable y= 20 */ Program No:-13 Program Name: Write a Java program that illustrates the folloiwng

Data Structures through java Lab

Department of M.C.A

HT.NO: 08F41F0040 a) Creation of simple packagae b) Accessing a package c) 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 { public void print1() {

Data Structures through java Lab

Department of M.C.A

HT.NO: 08F41F0040 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.c iam in abstract class B iam in Class c The sum of the numbers is :30 */

Data Structures through java Lab

Department of M.C.A

HT.NO: 08F41F0040

Program No:-14 Program Name: Writa a Java program that illustrates the following a) Handling predefined exceptions b) 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.java D:\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

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.java D:\dslab>java user : 15 Age is 15 D:\dslab>java user -15 AgeNegative: Age should be +ve at user.main(user.java:12) */

Program No:-15 Program 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.*; public class search

Data Structures through java Lab

Department of M.C.A

HT.NO: 08F41F0040 { 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) { for(int i=0;i<=a.length-1;i++)

Data Structures through java Lab

Department of M.C.A

HT.NO: 08F41F0040 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.java D:\mca_I_year>java search Enter the Size : 8 Enter the elements in sorted order 12 14 28 29 35 38 67 79 Enter the number to search : 79 Searching techniques 1. Linear Search 2. Binary Search Choose the searching technique : 2 Element is found at 8

Data Structures through java Lab

Department of M.C.A

HT.NO: 08F41F0040 Do you want to continue (0 - false & 1 - true): 1 Enter the number to search : 14 Searching techniques 1. Linear Search 2. Binary Search Choose the searching technique : 1 Ele. found at location 2 Do you want to continue (0 - false & 1 - true): 0 */

Program No:-16 Program 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"); for( i=0; i<List.length; i++)

Data Structures through java Lab

Department of M.C.A

HT.NO: 08F41F0040 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[]) { Listmethods s = new Listmethods();

Data Structures through java Lab

Department of M.C.A

HT.NO: 08F41F0040 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.QUIT Enter your choice(1-6) : 1 Enter LIST SIZE [== 10]: 10 Enter Element 0 :10 i= 10 Enter Element 1 :20 i= 20 Enter Element 2 :30 i= 30 Enter Element 3 :40 i= 40 Enter Element 4 :50 i= 50 Enter Element 5 :60

Data Structures through java Lab

Department of M.C.A

HT.NO: 08F41F0040 i= 60 Enter Element 6 :70 i= 70 Enter Element 7 :80 i= 80 Enter Element 8 :90 i= 90 Enter Element 9 :100 i= 100 The List has been Successfully Created: 1.CREATE 2.DISPLAY 3.REVERSE 4.SEARCH 5.DELETE 6.QUIT Enter your choice(1-6) : 2 The Created List is ... 10 20 30 40 50 60 70 80 90 100 1.CREATE 2.DISPLAY 3.REVERSE 4.SEARCH 5.DELETE 6.QUIT Enter your choice(1-6) : 3 The Reverse List is ... 100 90 80 70 60 50 40

Data Structures through java Lab

Department of M.C.A

HT.NO: 08F41F0040 30 20 10 1.CREATE 2.DISPLAY 3.REVERSE 4.SEARCH 5.DELETE 6.QUIT Enter your choice(1-6) : 4 Enter Element to Search: 50 Search Element Found at Index: 4 1.CREATE 2.DISPLAY 3.REVERSE 4.SEARCH 5.DELETE 6.QUIT Enter your choice(1-6) : 5 Enter Element to DELETE: 50 ELEMENT DELETED [-1 indicates as DELETED] 1.CREATE 2.DISPLAY 3.REVERSE 4.SEARCH 5.DELETE 6.QUIT Enter your choice(1-6) : 2 The Created List is ... 10 20 30 40 -1 60 70 80 90 100 1.CREATE 2.DISPLAY 3.REVERSE 4.SEARCH 5.DELETE

6.QUIT Enter your choice(1-6) : 6

Data Structures through java Lab

Department of M.C.A

HT.NO: 08F41F0040

*/

Data Structures through java Lab

Department of M.C.A

HT.NO: 08F41F0040

Program No:-17 Program Name: Write a Java program to implement the foloiwng using an array. a) Stack ADT b) 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

HT.NO: 08F41F0040 System.out.print(" } } } } 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); } } " + data[i]);

/*******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

HT.NO: 08F41F0040

Enter your Choice: 1 Enter Data: 10 Enter your Choice: 1 Enter Data: 20 Enter your Choice: 1 Enter Data: 30 Enter your Choice: 3 Top -> 30 20 Enter your Choice: 2 Poped element is: 30 Enter your Choice: 3 Top -> 20 10 Enter your Choice: 4 */ 10

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

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"); } else System.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"); } else System.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

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]); } else System.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

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

/***********OUTPUT********** D:\mca_I_year>java q Enter the Queue size : 3 QUEUE -------1.Insert 2.Delete 3.Display 4.Quit Enter the choice : 1 Enter element to insert : 34 New element is inserted QUEUE -------1.Insert 2.Delete 3.Display 4.Quit Enter the choice : 1 Enter element to insert : 23 New element is inserted QUEUE -------1.Insert 2.Delete 3.Display 4.Quit Enter the choice : 1 Enter element to insert : 56 New element is inserted

Data Structures through java Lab

Department of M.C.A

HT.NO: 08F41F0040 QUEUE -------1.Insert 2.Delete 3.Display 4.Quit Enter the choice : 1 Queue is full. can't perform Insertion. QUEUE -------1.Insert 2.Delete 3.Display 4.Quit Enter the choice : 3 Queue : 34 23 56 QUEUE -------1.Insert 2.Delete 3.Display 4.Quit Enter the choice : 2 First element is deleted QUEUE -------1.Insert 2.Delete 3.Display 4.Quit Enter the choice : 3 Queue : 23 56 QUEUE -------1.Insert 2.Delete 3.Display 4.Quit Enter the choice : 4 */

Data Structures through java Lab

Department of M.C.A

HT.NO: 08F41F0040

Program No:-18 Program 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

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

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 Postfix Enter the Infix expression : (A*(B+C)-D) Infix expression : (A*(B+C)-D) Postfix expression : ABC+*DD:\java\mca_I_year>java Postfix Enter 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

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

HT.NO: 08F41F0040 return res; } }

/***********OUTPUT********* D:\mca_I_year>javac Peval.java D:\mca_I_year>java Peval 234+5*+ Value of Postfix = 37

*/

Program No:-19 Program 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

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

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

HT.NO: 08F41F0040 } } } if(a.isEmpty()) System.out.println("Correctly Nested Parenthesis"); else System.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

HT.NO: 08F41F0040

Program No:-20 Program 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"); } else System.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

HT.NO: 08F41F0040 { front++; if(front==maxsize) front=0; nitems--; System.out.println("First element is deleted\n"); } else System.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

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

HT.NO: 08F41F0040 /***********OUTPUT********** D:\mca_I_year>java qu Enter the Queue size : 5 QUEUE -------1.Insert 2.Delete 3.Display 4.Quit 5. Palindrome Enter the choice : 1 Enter element to insert : m New element is inserted QUEUE -------1.Insert 2.Delete 3.Display 4.Quit 5. Palindrome Enter the choice : 1 Enter element to insert : a New element is inserted QUEUE -------1.Insert 2.Delete 3.Display 4.Quit 5. Palindrome Enter the choice : 1 Enter element to insert : d New element is inserted QUEUE -------1.Insert 2.Delete 3.Display 4.Quit 5. Palindrome Enter the choice : 1 Enter element to insert : a New element is inserted QUEUE -------1.Insert 2.Delete 3.Display 4.Quit 5. Palindrome Enter the choice : 1 Enter element to insert : m New element is inserted

Data Structures through java Lab

Department of M.C.A

HT.NO: 08F41F0040

QUEUE -------1.Insert 2.Delete 3.Display 4.Quit 5. Palindrome Enter the choice : 3 Queue : m a d a m QUEUE -------1.Insert 2.Delete 3.Display 4.Quit 5. Palindrome Enter the choice : 5 palindrome QUEUE -------1.Insert 2.Delete 3.Display 4.Quit 5. Palindrome Enter the choice : 2 First element is deleted QUEUE -------1.Insert 2.Delete 3.Display 4.Quit 5. Palindrome Enter the choice : 3 Queue : a d a m QUEUE -------1.Insert 2.Delete 3.Display 4.Quit 5. Palindrome Enter the choice : 5 Not a palindrome QUEUE -------1.Insert 2.Delete 3.Display 4.Quit 5. Palindrome Enter the choice : 4 */

Data Structures through java Lab

Department of M.C.A

HT.NO: 08F41F0040

Program No:-21 Program 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

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

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.Exit Enter 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

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.Exit Enter 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.Exit Enter your choice : 4 Contents of stack 34 23 12 Do you want to continue (1-Yes,0-No): 1 Stack process 1.Push 2.Pop 3.Peek 4.Display 5.Exit Enter your choice : 2 Do you want to continue (1-Yes,0-No): 1 Stack process 1.Push 2.Pop 3.Peek 4.Display 5.Exit Enter your choice : 4 Contents of stack 23 12 Do you want to continue (1-Yes,0-No): 5 */

Program No:-22 Program 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

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

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

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 LinkedDequeDemo Deque: [ BA] getFirst():B getLast():E Deque: [ BADE] removeFirst():B removeLast():A Deque: [ DE] size():2

Data Structures through java Lab

Department of M.C.A

HT.NO: 08F41F0040

*/

Program No:-23 Program 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

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"); } else System.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]); } else System.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

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.DISPLAY 4.Quit Enter your choice (1-4): 1 Enter Element to Insert: 5 New Element INSERTED. PRIORITY QUEUE -----------------------------------1.INSERT 2.DELETE 3.DISPLAY 4.Quit Enter your choice (1-4): 1 Enter Element to Insert: 20 New Element INSERTED.

Data Structures through java Lab

Department of M.C.A

HT.NO: 08F41F0040 PRIORITY QUEUE -----------------------------------1.INSERT 2.DELETE 3.DISPLAY 4.Quit Enter your choice (1-4): 1 Enter Element to Insert: 6 New Element INSERTED. PRIORITY QUEUE -----------------------------------1.INSERT 2.DELETE 3.DISPLAY 4.Quit Enter your choice (1-4): 3 THE PRIORITY QUEUE IS : 5 6 20 PRIORITY QUEUE -----------------------------------1.INSERT 2.DELETE 3.DISPLAY 4.Quit Enter your choice (1-4): 2 First Element DELETED PRIORITY QUEUE -----------------------------------1.INSERT 2.DELETE 3.DISPLAY 4.Quit Enter your choice (1-4): 3 THE PRIORITY QUEUE IS : 5 6 PRIORITY QUEUE -----------------------------------1.INSERT 2.DELETE 3.DISPLAY 4.Quit Enter your choice (1-4): 4 Program No:-24

Data Structures through java Lab

Department of M.C.A

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); else p.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; else p = p.right; } return null; }

Data Structures through java Lab

Department of M.C.A

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; else parent.right = null;

Data Structures through java Lab

Department of M.C.A

HT.NO: 08F41F0040 } if (p.left == null && p.right != null) { if (parent.left == p) parent.left = p.right; else parent.right = p.right; } if (p.left != null && p.right == null) { if (parent.left == p) parent.left = p.left; else parent.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

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." ); else System.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 BinarySearchTree Enter the size of the tree : 8 12 45 78 89 56 23 15 35 Preorder of tree : 12 45 23 15 35 78 56 89 Enter the element to search : 15

Data Structures through java Lab

Department of M.C.A

HT.NO: 08F41F0040 Searching item 15 found. Enter the node element to delete : 15 After deleting the node Preorder of tree : 12 45 23 35 78 56 89 D:\java\mca_I_year>java BinarySearchTree Enter the size of the tree : 8 12 45 78 89 56 23 15 35 Preorder of tree : 12 45 23 15 35 78 56 89 Enter the element to search : 91 Item not found Enter the node element to delete : 98 TNode not found : 98 After deleting the node Preorder of tree : 12 45 23 15 35 78 56 89

*/

Data Structures through java Lab

Department of M.C.A

HT.NO: 08F41F0040

Program No:-25 Program Name: Write a Java program that use recursive and non recursive functions to traverse the given binary tree in a) Preorder b) Inorder and c) 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

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

HT.NO: 08F41F0040

} } /*************OUTPUT ******** D:\java>javac BinaryTreeTraversal.java D:\java>java BinaryTreeTraversal Inorder : A B C D E F G H Preorder : E C A B D G F H postorder : B A D C F H G E

*/

Data Structures through java Lab

Department of M.C.A

HT.NO: 08F41F0040

Program No:-26 Program 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

HT.NO: 08F41F0040 class Graph { private final int MAX_VERTS = 20; private Vertex vertexList[]; // list of vertices private int adjMat[][]; // adjacency matrix private int nVerts; // current number of vertices private Queue theQueue; public Graph() // constructor { vertexList = new Vertex[MAX_VERTS]; // adjacency matrix adjMat = new int[MAX_VERTS][MAX_VERTS]; nVerts = 0; for(int j=0; j<MAX_VERTS; j++) // set adjacency for(int k=0; k<MAX_VERTS; k++) // matrix to 0 adjMat[j][k] = 0; theQueue = new Queue(); } // 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 bfs() // breadth-first search { // begin at vertex 0 vertexList[0].wasVisited = true; // mark it displayVertex(0); // display it theQueue.insert(0); // insert at tail int v2; while( !theQueue.isEmpty() ) // until queue empty, { int v1 = theQueue.remove(); // remove vertex at head // until it has no unvisited neighbors while( (v2=getAdjUnvisitedVertex(v1)) != -1 ) { vertexList[v2].wasVisited = true; // mark it

Data Structures through java Lab

Department of M.C.A

HT.NO: 08F41F0040 displayVertex(v2); // display it theQueue.insert(v2); // insert it } // end while } // end while(queue not empty) // queue is empty, so we're done for(int j=0; j<nVerts; j++) // reset flags vertexList[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'); // 1 theGraph.addVertex('C'); // 2 theGraph.addVertex('D'); // 3 theGraph.addVertex('E'); // 4 theGraph.addEdge(0, 1); // AB theGraph.addEdge(1, 2); // BC theGraph.addEdge(0, 3); // AD theGraph.addEdge(3, 4); // DE System.out.print("Visits: "); theGraph.bfs(); // breadth-first search System.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

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 array top = -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 vertices private int adjMat[][]; // adjacency matrix private int nVerts; // current number of vertices private StackX theStack; public Graph() // constructor { vertexList = new Vertex[MAX_VERTS]; // adjacency matrix adjMat = new int[MAX_VERTS][MAX_VERTS]; nVerts = 0; for(int j=0; j<MAX_VERTS; j++) // set adjacency for(int k=0; k<MAX_VERTS; k++) // matrix to 0 adjMat[j][k] = 0;

Data Structures through java Lab

Department of M.C.A

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 0 vertexList[0].wasVisited = true; // mark it displayVertex(0); // display it theStack.push(0); // push it while( !theStack.isEmpty() ) // until stack empty, { // get an unvisited vertex adjacent to stack top int v = getAdjUnvisitedVertex( theStack.peek() ); if(v == -1) // if no such vertex, theStack.pop(); else // if it exists, { vertexList[v].wasVisited = true; // mark it displayVertex(v); // display it theStack.push(v); // push it } } // end while // stack is empty, so we're done for(int j=0; j<nVerts; j++) // reset flags vertexList[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

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'); // 1 theGraph.addVertex('C'); // 2 theGraph.addVertex('D'); // 3 theGraph.addVertex('E'); // 4 theGraph.addEdge(0, 1); // AB theGraph.addEdge(1, 2); // BC theGraph.addEdge(0, 3); // AD theGraph.addEdge(3, 4); // DE System.out.print("Visits: "); theGraph.dfs(); // depth-first search System.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

HT.NO: 08F41F0040

Program No:-27 Program 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."); else System.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 pattern while (i < n) { if (pattern.charAt(j) == text.charAt(i)) { // Our match extends to length j+1 if (j == m-1) return i-m+1; // found full match i++; 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 pattern while (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

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 all i++; } } return fail; } } /****************OUTPUT*********** D:\mca_I_year>javac KMP.java D:\mca_I_year>java KMP hello,how he Searching for he in text of length 9 Found first match at shift=0 D:\mca_I_year>java KMP hello,how h Searching for h in text of length 9 Found first match at shift=0 D:\mca_I_year>java KMP hello,how l Searching for l in text of length 9 Found first match at shift=2 D:\mca_I_year>java KMP hello,how x Searching for x in text of length 9 No match.*/

Data Structures through java Lab

Department of M.C.A

HT.NO: 08F41F0040

Program No:-28 Program 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

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy