+ All Categories
Home > Documents > UNIT 5.doc

UNIT 5.doc

Date post: 24-Jan-2016
Category:
Upload: ram-anand
View: 239 times
Download: 0 times
Share this document with a friend
123
Unit V Object Oriented Programming in Java and Data Structures 1. Write a overview of Data Structure? The term data structure refers to a scheme for organizing related pieces of information in a computer’s memory. Data Strucutre Primitive Data Structure Non Primitive Data Structure Linear Non Linear Array Tree Linked List Graph Stack Queue Primitive Data Structure: These are the data structures which are directly supported by the languages, i.e., any operation will be directly performed in these data items. Few examples for primitive data structures are integers, real numbers, characters, etc., Non Primitive Data Structure: These data structures do not allow any specific instruction to be performed on the data item directly. The best example of this data structure is set of complex numbers. The linear and non linear data structures are Liners data structures : These data structures involves arranging the elements on a linear fashion .the following are the linear data structures they are arrays, linked lists stacks and queues. Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 89
Transcript
Page 1: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures 1. Write a overview of Data Structure?The term data structure refers to a scheme for organizing related pieces of information in a computer’s memory.

Data Strucutre

Primitive Data Structure Non Primitive Data Structure

Linear Non Linear

Array TreeLinked List GraphStackQueue

Primitive Data Structure: These are the data structures which are directly supported by the languages, i.e., any operation will be directly performed in these data items. Few examples for primitive data structures are integers, real numbers, characters, etc.,Non Primitive Data Structure: These data structures do not allow any specific instruction to be performed on the data item directly. The best example of this data structure is set of complex numbers.

The linear and non linear data structures are

Liners data structures : These data structures involves arranging the elements on a linear fashion .the following are the linear data structures they are arrays, linked lists stacks and queues.Arrays: array is an elementary data structure which holds the same data values in the contiguous memory locations. The elements of the array can be accessed sequentially /randomly.Linked list: Linked lists are data structures which support the logical adjacency of elements, and this is maintained using pointers.Stacks: A stack is a linear data structure, in which all insertions of elements takes place at one end and all deletions of elements takes place at other end.Nonlinear-data structure:These data structures involves representing the elements in hierarchical order is called trees, where as the elements representing in a arbitrary relationship is called graphs . Examples for the non-linear data structures are trees and graphs.Trees: Tree is a data structure which is helpful in variety of computer applications . A tree is data structure consisting of one or more nodes such that there is single root node and other child nodes. Graphs:Graph is a data structure mainly used in the applications such as finding shortest routes/paths, analysis of electrical circuits chemical compounds etc ,this data structure consists of a finite number of non-empty set of vertices as well as edges.

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 89

Page 2: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures 2. Explain Bubble Sorting?Bubble is simple sorting algorithm. The working of bubble sort can be explained as: We start at the left end of the line and compare the two objects in position 0 and 1. if the one of the left object is larger than right object, then we swap the second object. If the left is smaller than right object, then we don’t do anything. Next we move towards next position and compare the next two objects at position 1 and 2, and same process is continued. We have to continue down the line until we reach the right end. After completion of first round the largest object will be at right end.

After the first pass through all the data, we have N-1 elements to be sorted. We go back and start another pass from the left end of the line and continue the process again on N-1 elements. After second pass the next largest object will the at right end. Similarly the process is continue unto all the objects are in order and there no swaps.

import java.util.Scanner;public class BubbleSort1 { static int[] a; int n; BubbleSort1(int t) { a=new int[t]; n=t; } public void display()

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

System.out.println(a[i]+" ");System.out.println(" ");

}public void bubbleSort(){ int i, j; for(i=n-1;i>0;i--) for(j=0;j<i;j++) if(a[j]>a[j+1]) { int t=a[j]; a[j]=a[j+1]; a[j+1]=t; }}public static void main(String arg[]){ Scanner sc=new Scanner(System.in); int n; System.out.println("Enter number of elements");

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 90

Page 3: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures n=sc.nextInt(); BubbleSort1 obj=new BubbleSort1(n); System.out.println("Enter "+n+"values"); for(int i=0;i<n;i++) a[i]=sc.nextInt(); System.out.println("Elements before sorting"); obj.display(); obj.bubbleSort(); System.out.println("Elements after sorting"); obj.display(); }}

3. Write about Selection Sorting?The selection sort is more efficicient than bubble sort by reducing the number of swaps. Selection sort is noted for its simplicity, and also has performance advantages over more complicated algorithms in certain situations.

Selection sort will not require not more than n-1 interchanges. Suppose x is an array of size n stored in memory. The selection sort algorithm first selects the smallest element in the array x and place it at array position 0; then it selects the next smallest element in the array x and place it at array position 1. It simply continues this procedure until it places the biggest element in the last position of the array.

The array is passed through (n-1) times and the smallest element is placed in its respective position in the array as detailed below:

Pass 1:Find the location j of the smallest element in the array x [0], x[1], . . . . x[n-1], and then interchange x[j] with x[0]. Then x[0] is sorted.

Pass 2:Leave the first element and find the location j of the smallest element in the sub-array x[1], x[2], . . . . x[n-1], and then interchange x[1] with x[j]. Then x[0], x[1] are sorted.

Pass 3: Leave the first two elements and find the location j of the smallest element in the sub-array x[2], x[3], . . . . x[n-1], and then interchange x[2] with x[j]. Then x[0], x[1], x[2] are sorted.

Pass (n-1):Find the location j of the smaller of the elements x[n-2] and x[n-1], and then interchange x[j] and x[n-2]. Then x[0], x[1], . . . . x[n-2] are sorted. Of course, during this pass x[n-1] will be the biggest element and so the entire array is sorted.

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 91

Page 4: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures import java.util.Scanner;public class Selection { static int[] a; int n; Selection(int t) { a=new int[t]; n=t; } public void display() { for(int i=0;i<n;i++) System.out.println(a[i]+" ");

System.out.println(" "); } public void insertionSort() { int i,j,t; for(i=0;i<n-1;i++) { t=i; for(j=i+1;j<n;j++) if(a[j]<a[t]) t=j; swap(i,t); } } public void swap(int i,int j) { int temp=a[i]; a[i]=a[j]; a[j]=temp; } public static void main(String arg[]) { Scanner sc=new Scanner(System.in); int n; System.out.println("Enter number of elements");

n=sc.nextInt();Selection obj=new Selection(n);

System.out.println("Enter "+n+"values"); for(int i=0;i<n;i++) a[i]=sc.nextInt(); System.out.println("Elements before sorting"); obj.display(); obj.insertionSort(); System.out.println("Elements after sorting"); obj.display(); }}

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 92

Page 5: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures 4. What is Insertion Sort? ExplainInsertion is one of the best sorting technique available. It is twice as fast as the bubble sort. Insertion sort is implemented by inserting a particular element at the appropriate position. In this method, the first iteration start with comparison of 1st element with the 0th element. In the second iteration 2nd element is compared with the 0th and 1st

element. In general, in every iteration an element is compared with all elements before it. During comparison if it is found that the element in question can be inserted at a suitable position then space is created for it by shifting the other elements one position to the right and inserting the element at the suitable position. This procedure is repeated for the elements in the list.

import java.util.Scanner;public class Insertion{

static Scanner sc=new Scanner(System.in);int a[];static int n;public Insertion(int t){

a=new int[t];}public void display(){

for(int i=0;i<n;i++)System.out.println(" "+a[i]);

System.out.println("");}public void insertionSort(){

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

int t=a[i];int j=i;while(j>0 && a[j-1]>=t){

a[j]=a[j-1];--j;

}a[j]=t;

}}public void insert(){

System.out.println("Enter the "+n+"values");for(int i=0;i<n;i++)

a[i]=sc.nextInt();}public static void main(String arg[])

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 93

Page 6: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures

{System.out.println("Enter No of elements");n=sc.nextInt();Insertion obj=new Insertion(n);obj.insert();System.out.println("Elements before sorting:");obj.display();obj.insertionSort();System.out.println("Elements after sorting:");obj.display();

}}

5. Write about Quick Sort?The quick sort was invented by Prof. C. A. R. Hoare in the early 1960’s. It was one of the first more efficient sorting algorithms. It is an example of a class of algorithms that work by what is usually called “divide and conquer”.

In essence, the quick sort algorithm partitions the original array by rearranging it into two groups. The first group contains those elements less than some arbitrary chosen value taken from the set, and the second group contains those elements greater than or equal to the chosen value.

The chosen value is known as the pivot element. Once the array has been rearranged in this way with respect to the pivot, the very same partitioning is recursively applied to each of the two subsets. When all the subsets have been partitioned and rearranged, the original array is sorted.

The function partition() makes use of two pointers up and down which are moved toward each other in the following fashion:

1. Repeatedly increase the pointer ‘up’ until a[up] >= pivot.

2. Repeatedly decrease the pointer ‘down’ until a[down] <= pivot.

3. If down > up, interchange a[down] with a[up]

4. Repeat the steps 1, 2 and 3 till the ‘up’ pointer crosses the ‘down’ pointer. If ‘up’ pointer crosses ‘down’ pointer, the position for pivot is found and place pivot element in ‘down’ pointer position.

The program uses a recursive function quick sort(). The algorithm of quick sort function sorts all elements in an array ‘a’ between positions ‘low’ and ‘high’.

1. It terminates when the condition low >= high is satisfied. This condition will be satisfied only when the array is completely sorted.

2. Here we choose the first element as the ‘pivot’. So, pivot = x[low]. Now it calls the partition function to find the proper position j of the element

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 94

Page 7: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures

x[low] i.e. pivot. Then we will have two sub-arrays x[low], x[low+1], . . . . . . . x[j-1] and x[j+1], x[j+2], . . .x[high].

3. It calls itself recursively to sort the left sub-array x[low], x[low+1], . . . . . . . x[j-1] between positions low and j-1 (where j is returned by the partition function).

4. It calls itself recursively to sort the right sub-array x[j+1], x[j+2], . . .x[high] between positions j+1 and high.

import java.util.Scanner;public class QuickSort { static int[] a; int n; QuickSort(int t) { a=new int[t]; n=t; } public void display() { for(int i=0;i<n;i++) System.out.println(a[i]+" ");System.out.println(" "); } public void quick(int left,int right) { if(right-left<=0) return; else { int piv=a[right]; int t=partition(left,right,piv); quick(left,t-1); quick(t+1,right); } } public int partition(int left,int right,int piv) { int l1=left-1; int r1=right; while(true) { while(a[++l1]<piv) ; while(r1>0 && a[--r1]>piv) ; if(l1>=r1)

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 95

First Iteration

41 79 65 35 21 48 59 87 52 28Pivot(compare it with right end and swapif(re<p)

28 79 65 35 21 48 59 87 52 41(now p is at re & compare with ele At left side and next to the ele just swapped)

28 41 65 35 21 48 59 87 52 79

28 21 65 35 41 48 59 87 52 79

28 21 41 35 65 48 59 87 52 79

28 21 35 41 65 48 59 87 52 79

41 28 21 35 65 48 59 52 79

Page 8: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures break; else swap(l1,r1); } swap(l1,right); return l1; } public void swap(int t1,int t2) { int temp=a[t1]; a[t1]=a[t2]; a[t2]=temp; } public static void main(String arg[]) { Scanner sc=new Scanner(System.in); int n; System.out.println("Enter number of elements"); n=sc.nextInt(); QuickSort obj=new QuickSort(n); System.out.println("Enter "+n+"values"); for(int i=0;i<n;i++) a[i]=sc.nextInt(); System.out.println("Elements before sorting"); obj.display(); obj.quick(0, n-1); System.out.println("Elements after sorting"); obj.display(); } }

6.What is linked list? Explain about all operation of linked lists. Describe the advantages of linked lists over linear lists and disadvantages of linked lists?A Linked list refers to a set of items organized sequentially. An array is an example of Linked list. In an array the sequential organization is provided implicitly by its index. We use the index for accessing and manipulation of array elements. One major problem with the arrays is that, the size of an array must be specified precisely at the beginning. This may be a difficult task in many real life applications.

To overcome this we use the concept of linked list. The items are inserted and deleted dynamically. Linked lists and arrays resembles as same, but a linked list is a dynamic data structure because its size is variable but where as array is static data structure because its size is fixed. Each item in the list part of a structure also contains a link to the structure containing the next item.

Each structure of the list is called a node and consists of two fields, one contains the item and the other contains the address of the next item in the list. A

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 96

Page 9: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures

linked list is therefore a collection of structures ordered not by their physical placement in memory but by logical links that are stored as part of the data in the structure itself. Such a structure is represented as follows:class node{

int item;node next;

}The first member is an integer item and the second a pointer to the next node in the list called as self referential as shown below.

node

item nextThe most common operations performed on the Data structure

Creation of a list: This operation involves creation of a link. It creates the first node which is assigned to head node. Insertion: This operation involves adding a new element to the data structure. Thus it enables us to insert any particular element in any specific position.Deletion: This operation involves deleting an element from the Data Structure. Any unsorted element can be removed from the existing data structure.Traversal: This operation involves accessing the elements of data through a process.Sorting: This operation enables us to rearrange the data into a logical order.Searching: This operation helps to find the position of the element in the given data structure.Merging: This operation makes it possible to combine the elements of two similar Data Structure into one Data Structure, which is the merged data structure.Printing: This operation involves displaying the linked list.Counting: This operation involves counting the number of elements in the list.

Advantages of the Linked Lists:1. We can dynamically allocate memory space as needed.2. We can dynamically also release the unused space in the situation where the

allocated space to be more.3. With the feasibility of dynamic allocation as well as dynamic release of

memory space effective memory utilization is possible.4. Operations related to data elements like insertions or deletions are more

simplified.5. Operations like insertions or deletions consumes less time.6. Linked list provides flexibility in allowing the items be arranged efficiently.

This helps in the quick accessing of items in the list.

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 97

Page 10: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures

disadvantages of linked lists:1. The major limitation of linked list is that the access to any arbitrary item is

little cumbersome and time consuming 2. when ever we deal with fixed length lists it would be better to use an array

rather than a linked list . 3. Linked list will consume more storage space than an array with same number

of items this is because each item has an additional link field7.Write a short notes on linked list and explain the types of linked list?A Linked list refers to a set of items organized sequentially. An array is an example of Linked list. In an array the sequential organization is provided implicitly by its index. We use the index for accessing and manipulation of array elements. One major problem with the arrays is that, the size of an array must be specified precisely at the beginning. This may be a difficult task in many real life applications.

To overcome this we use the concept of linked list. The items are inserted and deleted dynamically. Linked lists and arrays resembles as same, but a linked list is a dynamic data structure because its size is variable but where as array is static data structure because its size is fixed. Each item in the list part of a structure also contains a link to the structure containing the next item.

Each structure of the list is called a node and consists of two fields, one contains the item and the other contains the address of the next item in the list. A linked list is therefore a collection of structures ordered not by their physical placement in memory but by logical links that are stored as part of the data in the structure itself. Such a structure is represented as follows:class node{

int item;node next;

}The first member is an integer item and the second a pointer to the next node in the list called as self referential as shown below.

node

item nextThere are several kinds of linked lists, including single-linked lists, double-linked lists, and binary trees. Each type is suited for certain types of data storage. The one thing that these lists have in common is that the links between data items are defined by information that is contained in the items themselves, in the form of pointers.Application of linked lists:

1. Linked lists are used in polynomial manipulation2. Representation of trees and graphsa) Single Linked Lists: a single linked list is represented expanding each node to

a link to the next node as shown below

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 98

Page 11: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures

First Last

`

In the above figure ‘first’ is a variable which contains an address which gives the location of the first node. Each node is divided into two fields. The first field known ‘as information field, gives the information of the element and the second field known as link field, contains the address of the next node.

Doubly Linked List:In doubly linked list, one can move in both direction. Since each node contains two link components instead of one, it requires more memory. This doubly linked list would be as follows:

First LastThe link which denotes the previous node is called left link and link which denotes a successor node is called right link. Thus moving in either directions is possible through a doubly linked list.

Circular Linked List:The circular linked list suppresses the limitations of moving is only one direction. This is done by providing a link from the last node to the first node.

First` LastThis type of listing is known as circular linked listing. In this type of list, we can move in one direction only but can come to the beginning of the node unlike in the case of single linked list.Circular Double Linked list:This is linked list similar to double linked list but the last node provides the link to the first node.

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 99

Page 12: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures

8. Write about Single Linked List?Single linked lists: A single linked lists is also called as one-way list. It is a linear collection of data elements, called nodes, where as the linear order is given by means of a pointers i.e, each node is divided into 2 parts the first part contains the information of the node& the second part, called link field contains the address of the next node in the list. The pictorial representation of Node is as follows.

Node StructureINFO LINK

Eg:The above example having four nodes. Each node is pictured with 2 parts,

namely. INFO & Link. The INFO part of each node contains the value & LINK part contains the address of the next node. Further, more the above lists contains a pointer variable-START- which contains the address of the first node of the list. Hence there is an arrow drawn from start to first Node. Moreover, the last-node’s Link-part contains null value which indicates the end of the lists.

The list is said to be empty list (or) null list when there are no nodes at all. This can be achieved by assigning the Null pointer to the START pointer. The Node declaration for the single linked list containing integer is as follows.

class Node{

int info;Node link;

}

import java.util.Scanner;

class Node{ int data; Node link;}public class SLL { Node start=new Node(); Node x=new Node(); SLL(){ start=null;}public void create() { Scanner sc=new Scanner(System.in); Node temp=new Node(); System.out.println("Enter the data to be inserted"); temp.data=sc.nextInt();

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 100

Page 13: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures sc.skip("\n"); temp.link=null; if(start==null) { start=temp; x=start; } else { x.link=temp; x=temp; } System.out.print("\nDo you want to insert one more node yes(1) or no(0)"); char ch; ch=sc.nextLine().charAt(0); if(ch=='y') create(); else return;}public void display(){ Node temp=new Node(); if(start==null) System.out.println("Stack is empty"); else { System.out.print("\nStart-->"); temp=start; while(temp!=null) { System.out.print(temp.data+"-->"); temp=temp.link; } System.out.println("End"); } }

public void insert(int pos,int data){ Node temp=new Node(); temp.data=data; temp.link=null; if(pos==1) { temp.link=start; start=temp; } else

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 101

Page 14: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures { int t=2; x=start; while(t<pos && x.link!=null ) { t++; x=x.link; } temp.link=x.link; x.link=temp; }}public void remove(int pos){ if(start==null) { System.out.println("Stack is empty"); } else { Node temp=new Node(); temp=start; if(pos==1) { start=start.link; } else { temp=start; int t=2; while(t<=pos && temp!=null) { x=temp; temp=temp.link; t++; } if(temp!=null) { x.link=temp.link; } else { System.out.println("Position does not exist"); return; } } System.out.println("Deleted data is"+temp.data); }}

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 102

Page 15: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures public void sort(){ Node t1=new Node(); Node t2=new Node(); for(t1=start;t1.link!=null;t1=t1.link) for(t2=t1.link;t2!=null;t2=t2.link) if(t1.data>t2.data) { int t=t1.data; t1.data=t2.data; t2.data=t; }}

public static void main(String arg[]){ Scanner sc=new Scanner(System.in); SLL obj=new SLL(); byte ch; do { System.out.println("**********************Menu***************"); System.out.println("\n\t1.Create\n\t2.Insert\n\t3.Delete\n\t4.Sort\n\t5.Display\n\t6.Exit"); System.out.println("Enter your choice"); ch=sc.nextByte(); switch(ch) { case 1:obj.create(); break; case 2: int pos,data; System.out.println("Enter the position and data to be inserted"); pos=sc.nextInt(); data=sc.nextInt(); obj.insert(pos, data); break; case 3: System.out.println("Enter the position to be deleted"); pos=sc.nextInt(); obj.remove(pos);break; case 4: obj.sort(); obj.display();break; case 5: obj.display();break;

case 6: System.exit(0); } }while(ch!=6); }}

9. Write about Circular Single Linked ListIn this there is no starting and ending point.Every node contains to some other node and no node contains null value in its reference.

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 103

Page 16: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures import java.util.Scanner;class Node{ int data; Node link;}public class CSLL {Node start=new Node();Node x=new Node();public CSLL(){ start=null;}public void create(){ Scanner sc=new Scanner(System.in); Node temp=new Node(); System.out.println("Enter the data to be inserted"); temp.data=sc.nextInt(); sc.skip("\n"); if(start==null) { start=temp; x=start; } else { x.link=temp; x=temp; } System.out.print("\nDo you want to insert one more node yes(1) or no(0)"); char ch; ch=sc.nextLine().charAt(0); if(ch=='y') create(); else temp.link=start;}public void display(){ if(start==null) { System.out.println("List is empty"); } else { Node temp=new Node(); temp=start; do

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 104

Page 17: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures { System.out.print(temp.data+"-->"); temp=temp.link; }while(temp!=start); System.out.println(temp.data); }}public void insert(int pos,int data){ Node temp=new Node(); temp.data=data; x=start; if(pos==1) { while(x.link!=start) x=x.link; x.link=temp; temp.link=start; start=temp; } else { int t=2; x=start; while(t<pos && x.link!=start) { x=x.link; t++; } temp.link=x.link; x.link=temp; }}public void remove(int pos){ if(start==null) { System.out.println("List is empty"); } else { x=start; Node temp=new Node(); temp=start; if(pos==1) { while(x.link!=start) x=x.link; start=start.link;

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 105

Page 18: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures x.link=start; System.out.println("Deleted elementis"+temp.data); } else { int t=2; temp=temp.link; while(t<pos && temp!=start) { x=temp; temp=temp.link; t++; } if(temp!=start) { System.out.println("Deleted element is"+temp.data); x.link=temp.link; } else { System.out.println("Position does not exists"); } } }}public void sort(){ Node t1=new Node(); Node t2=new Node(); for(t1=start;t1.link!=start;t1=t1.link) { for(t2=t1.link;t2!=start;t2=t2.link) { if(t1.data>t2.data) { int t=t1.data; t1.data=t2.data; t2.data=t; } } }}public static void main(String arg[]){ Scanner sc=new Scanner(System.in); CSLL obj=new CSLL(); byte ch; do

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 106

Page 19: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures { System.out.println("**********************Menu***************"); System.out.println("\n\t1.Create\n\t2.Insert\n\t3.Delete\n\t4.Sort\n\t5.Display\n\t6.Exit"); System.out.println("Enter your choice"); ch=sc.nextByte(); switch(ch) { case 1:obj.create(); break; case 2: int pos,data; System.out.println("Enter the position and data to be inserted"); pos=sc.nextInt(); data=sc.nextInt(); obj.insert(pos, data); break; case 3: System.out.println("Enter the position to be deleted"); pos=sc.nextInt(); obj.remove(pos);break; case 4: obj.sort(); obj.display();break; case 5: obj.display();break;

case 6: System.exit(0); } }while(ch!=6); }}

10. Explain about Double Linked List:

import java.util.Scanner;

class Node {

Node left; int data; Node right;}

public class DLL {

Node start = new Node(); Node x = new Node(); public DLL() { start=null; } public void create() {

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 107

Page 20: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures Scanner sc=new Scanner(System.in); Node temp=new Node(); temp.left=null; temp.right=null; System.out.println("Enter the data to be inserted"); temp.data=sc.nextInt(); sc.skip("\n"); if(start==null) { start=temp; x=temp; } else { x.right=temp; temp.left=x; x=temp; } System.out.print("\nDo you want to insert one more node yes(y) or no(n)"); char ch; ch=sc.nextLine().charAt(0); if(ch=='y') create(); else return; } public void display() { if(start==null) { System.out.println("Lis is empty"); } else { Node x=new Node(); Node temp=new Node(); temp=start; System.out.print("\nForward Traversing:Start-->"); while(temp!=null) { System.out.print(temp.data+"-->"); temp=temp.right; } System.out.print("End"); System.out.print("\nBackward Traversing:End-->"); temp=start; while(temp.right!=null) temp=temp.right; while(temp!=null)

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 108

Page 21: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures { System.out.print(temp.data+"-->"); temp=temp.left; } System.out.print("Start"); } } public void insert(int pos,int data) { Node temp=new Node(); temp.data=data; temp.left=null; temp.right=null; if(pos==1) { temp.right=start; start.left=temp; start=temp; } else { x=start; int t=2; while(t<pos && x.right!=null) { x=x.right; t++; } if(x.right!=null) { temp.right=x.right; temp.left=x; x.right.left=temp; x.right=temp; } else { x.right=temp; temp.left=x; } } } public void remove(int pos) { if(start==null) { System.out.println("List is empty"); } else

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 109

Page 22: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures { Node temp=new Node(); if(pos==1) { temp=start; start=start.right; start.left=null; } else { int t=2; while(t<=pos && temp!=null) { temp=temp.right; t++; } if(temp!=null) { temp.left.right=temp.right; temp.right.left=temp.left; } else { System.out.println("Position does not exists"); } } } } public void sort(){ Node t1=new Node(); Node t2=new Node(); for(t1=start;t1.right!=null;t1=t1.right) for(t2=t1.right;t2!=null;t2=t2.right) if(t1.data>t2.data) { int t=t1.data; t1.data=t2.data; t2.data=t; }} public static void main(String arg[]) { Scanner sc=new Scanner(System.in); DLL obj=new DLL(); byte ch; do {

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 110

Page 23: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures System.out.println("\n**********************Menu***************"); System.out.println("\n\t1.Create\n\t2.Insert\n\t3.Delete\n\t4.Sort\n\t5.Display\n\t6.Exit"); System.out.println("Enter your choice"); ch=sc.nextByte(); switch(ch) { case 1:obj.create(); break; case 2: int pos,data; System.out.println("Enter the position and data to be inserted"); pos=sc.nextInt(); data=sc.nextInt(); obj.insert(pos, data); break; case 3: System.out.println("Enter the position to be deleted"); pos=sc.nextInt(); obj.remove(pos);break; case 4: obj.sort(); obj.display();break; case 5: obj.display();break; case 6: System.exit(0); } }while(ch!=6); }}

11.Explain about Circular Double Linked Listimport java.util.Scanner;

class Node {

Node left; int data; Node right;}

public class CDLL {

Node start = new Node(); Node x = new Node(); public CDLL() { start=null; } public void create() { Scanner sc=new Scanner(System.in); Node temp=new Node(); System.out.println("Enter the data to be inserted"); temp.data=sc.nextInt();

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 111

Page 24: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures sc.skip("\n"); if(start==null) { start=temp; x=temp; } else { x.right=temp; temp.left=x; x=temp; } System.out.print("\nDo you want to insert one more node yes(y) or no(n)"); char ch; ch=sc.nextLine().charAt(0); if(ch=='y') create(); else { start.left=temp; temp.right=start; } } public void display() { if(start==null) { System.out.println("Lis is empty"); } else { Node x=new Node(); Node temp=new Node(); temp=start; System.out.print("\nForward Traversing:"); do { System.out.print(temp.data+"-->"); temp=temp.right; }while(temp!=start); System.out.print(temp.data); System.out.print("\nBackward Traversing:"); temp=start.left; do { System.out.print(temp.data+"-->"); temp=temp.left; }while(temp!=start.left); System.out.print(temp.data);

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 112

Page 25: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures } } public void insert(int pos,int data) { Node temp=new Node(); temp.data=data; if(pos==1) { start.left.right=temp; temp.left=start.left; temp.right=start; start.left=temp; start=temp; } else { x=start; int t=2; while(t<pos && x.right!=start) { x=x.right; t++; } if(x.right!=start) { temp.right=x.right; temp.left=x; x.right.left=temp; x.right=temp; } else { x.right=temp; temp.left=x; temp.right=start; start.left=temp; } } } public void remove(int pos) { if(start==null) { System.out.println("List is empty"); } else { Node temp=new Node(); if(pos==1)

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 113

Page 26: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures { temp=start; start.left.right=start.right; start.right.left=start.left; start=start.right; System.out.println("Deleted element is:"+temp.data); } else { int t=2; temp=start.right; while(t<pos && temp!=start) { temp=temp.right; t++; } if(temp!=start) { System.out.println(pos); System.out.println("Deleted element is:"+temp.data); temp.left.right=temp.right; temp.right.left=temp.left; } else { System.out.println("Position does not exists"); } } } } public void sort(){ Node t1=new Node(); Node t2=new Node(); for(t1=start;t1.right!=start;t1=t1.right) for(t2=t1.right;t2!=start;t2=t2.right) if(t1.data>t2.data) { int t=t1.data; t1.data=t2.data; t2.data=t; }} public static void main(String arg[]) { Scanner sc=new Scanner(System.in); CDLL obj=new CDLL(); byte ch;

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 114

Page 27: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures do { System.out.println("\n**********************Menu***************"); System.out.println("\n\t1.Create\n\t2.Insert\n\t3.Delete\n\t4.Sort\n\t5.Display\n\t6.Exit"); System.out.println("Enter your choice"); ch=sc.nextByte(); switch(ch) { case 1:obj.create(); break; case 2: int pos,data; System.out.println("Enter the position and data to be inserted"); pos=sc.nextInt(); data=sc.nextInt(); obj.insert(pos, data); break; case 3: System.out.println("Enter the position to be deleted"); pos=sc.nextInt(); obj.remove(pos);break; case 4: obj.sort(); obj.display();break; case 5: obj.display();break; case 6: System.exit(0); } }while(ch!=6); }}

12. Write about Stack?A stack is a list of elements in which an element may be inserted or deleted only at one end, called the top of the stack. Stacks are sometimes known as LIFO (last in, first out) lists.

As the items can be added or removed only from the top i.e. the last item to be added to a stack is the first item to be removed.

The two basic operations associated with stacks are:

Push: is the term used to insert an element into a stack. Pop: is the term used to delete an element from a stack.

“Push” is the term used to insert an element into a stack. “Pop” is the term used to delete an element from the stack.

All insertions and deletions take place at the same end, so the last element added to the stack will be the first element removed from the stack. When a stack is created, the stack base remains fixed while the stack top changes as elements are added and removed. The most accessible element is the top and the least accessible element is the bottom of the stack.

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 115

Page 28: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures Representation of Stack:

Let us consider a stack with 6 elements capacity. This is called as the size of the stack. The number of elements to be added should not exceed the maximum size of the stack. If we attempt to add new element beyond the maximum size, we will encounter a stack overflow condition. Similarly, you cannot remove elements beyond the base of the stack. If such is the case, we will reach a stack underflow condition.

When a element is added to a stack, the operation is performed by push(). Figure below shows the creation of a stack and addition of elements using push().

When an element is taken off from the stack, the operation is performed by pop(). Figure below shows a stack initially with three elements and shows the deletion of elements using pop().

Applications of stacks:7. Stack is used by compilers to check for balancing of parentheses,

brackets and braces.8. Stack is used to evaluate a postfix expression.9. Stack is used to convert an infix expression into postfix/prefix form.10. In recursion, all intermediate arguments and return values are stored on

the processor’s stack.11. During a function call the return address and arguments are pushed onto

a stack and on return they are popped off.12. Depth first search uses a stack data structure to find an element from a

graph.

13. Write a program for stack using Array?import java.util.Scanner;public class StackAry{

final int MAX=5;int top;

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 116

Page 29: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures

int stk[];public StackAry(){

stk=new int[MAX];top=-1;

}public void push(int data){

if(top==MAX-1)System.out.println("Stack is overflow");

elsestk[++top]=data;

}public void pop(){

if(top==-1)System.out.println("Stack is underflow");

elseSystem.out.println("Data deleted is :"+stk[top--]);

}public void peek(){

if(top==-1)System.out.println("Stack is empty");

else if(top==MAX-1)System.out.println("Stack is full");

elseSystem.out.println("Top is at the position of"+(top+1)+"And

element at that position is"+stk[top]);}public void display(){

if(top==-1)System.out.println("Stack is empty");

else{

System.out.print("\nStack elements are Top->");int temp=top;while(temp>=0){

System.out.print(stk[temp]+" ");temp--;

}}

}public static void main(String arg[]){

Scanner sc=new Scanner(System.in);

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 117

Page 30: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures

StackAry obj=new StackAry();int data;Byte ch;do{

System.out.println("\n*******************Menu*********************");

System.out.println("\t1.Push\n\t2.Pop\n\t3.Peek\n\t4.Display\n\t5.Exit\n\tEnter your choice");

ch=sc.nextByte();switch(ch){

case 1: System.out.println("Enter the data:");data=sc.nextInt();obj.push(data);break;

case 2: obj.pop(); break;case 3: obj.peek(); break;case 4: obj.display(); break;

}}while(ch!=5);

}}

14. Stack Using Linked ListWe can represent a stack as a linked list. In a stack push and pop operations are performed at one end called top. We can perform similar operations at one end of list using top pointer.

import java.util.Scanner;class Node{

int data;Node link;

}

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 118

Page 31: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures public class Stackll{

Node top=new Node();public Stackll(){

top=null;}public void push(int data){

Node temp=new Node();temp.data=data;temp.link=null;if(top==null)

top=temp;else{

temp.link=top;top=temp;

}}public void pop(){

if(top==null)System.out.println("Stack is empty");

else{

System.out.println("Popped element is:"+top.data);top=top.link;

}}public void peek(){

if(top==null)System.out.println("Stack is empty");

else{

Node temp=new Node();temp=top;int count=0;while(temp!=null){

temp=temp.link;count++;

}System.out.println("Total no of elements are:"+count+"and Top

element is "+top.data);}

}public void display()

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 119

Page 32: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures

{if(top==null)

System.out.println("Stack is empty");else{

Node temp=new Node();temp=top;System.out.print("Top-->");while(temp!=null){

System.out.print(temp.data+"-->");temp=temp.link;

}System.out.println("End");

}}public static void main(String arg[]){

Scanner sc=new Scanner(System.in);Stackll obj=new Stackll();int data;Byte ch;do{

System.out.println("\n*******************Menu*********************");

System.out.print("\t1.Push\n\t2.Pop\n\t3.Peek\n\t4.Display\n\t5.Exit\n\tEnter your choice:");

ch=sc.nextByte();switch(ch){

case 1: System.out.println("Enter the data:");data=sc.nextInt();obj.push(data);break;

case 2: obj.pop(); break;case 3: obj.peek(); break;case 4: obj.display(); break;

}}while(ch!=5);

}}

15. Evaluation of Expression:The place where stacks are frequently used is in evaluation of arithmetic expression. A polish mathematician Jan Lukasiewicz suggested a notation called polish notation, which gives two alternatives to represent an arithmetic expression. The notation are prefix and postfix notations. The fundamental property of polish notation is that the

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 120

Page 33: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures order in which the operations are to be performed is completely determined by the positions of the operators and operands in the expression.An algebraic expression can be represented using three different notations. They are infix, postfix and prefix notations:

Infix: It is the form of an arithmetic expression in which we fix (place) the arithmetic operator in between the two operands.

Example: (A + B) * (C - D)

Prefix: It is the form of an arithmetic notation in which we fix (place) the arithmetic operator before (pre) its two operands. The prefix notation is called as polish notation (due to the polish mathematician Jan Lukasiewicz in the year 1920).

Example: * + A B – C D

Postfix: It is the form of an arithmetic expression in which we fix (place) the arithmetic operator after (post) its two operands. The postfix notation is called as suffix notation and is also referred to reverse polish notation.

Example: A B + C D - *

The three important features of postfix expression are:

1. The operands maintain the same order as in the equivalent infix expression.

2. The parentheses are not needed to designate the expression un-ambiguously.

3. While evaluating the postfix expression the priority of the operators is no longer relevant.

We consider five binary operations: +, -, *, / and $ or (exponentiation). For these binary operations, the following in the order of precedence (highest to lowest):

Operator Precedence Value

Exponentiation ($ or or ^) Highest 3

*, / Next highest 2

+, - Lowest 1

Conversion from infix to postfix: Procedure to convert from infix expression to postfix expression is as follows:

1. Scan the infix expression from left to right.

2. a) If the scanned symbol is left parenthesis, push it onto the stack.

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 121

Page 34: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures

b) If the scanned symbol is an operand, then place directly in the postfix expression (output).

c) If the symbol scanned is a right parenthesis, then go on popping all the items from the stack and place them in the postfix expression till we get the matching left parenthesis.

d) If the scanned symbol is an operator, then go on removing all the operators from the stack and place them in the postfix expression, if and only if the precedence of the operator which is on the top of the stack is greater than (or equal) to the precedence of the scanned operator and push the scanned operator onto the stack otherwise, push the scanned operator onto the stack.

import java.util.Scanner;class Stack{ char op[]=new char[50]; int top;}public class InfixToPost {String in;char post[]=new char[50];int inlen,i,j,r;char inchar;Stack st=new Stack();public InfixToPost(){ st.top=-1; r=0;}public int rank(char x){ return (x=='*'||x=='+'||x=='-'||x=='/'||x=='^'?-1:1);}public int precedence(char x){ if(x=='^') return 3; else if(x=='*'||x=='/') return 2; else if(x=='+'||x=='-') return 1; return 0; }public void read(){ Scanner sc=new Scanner(System.in); System.out.println("Enter the expression"); in=sc.next().toLowerCase(); inlen=in.length(); }

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 122

Page 35: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures public void convert(){ read(); for(j=0,i=0;i<inlen;i++) { inchar=in.charAt(i); r=r+rank(inchar); if(r<0) { System.out.println("Invalid Expression"); System.exit(0); } if(inchar>='a'&& inchar<='z') post[j++]=inchar; else if(inchar=='(') st.op[++st.top]=inchar; else if(inchar==')') { while(st.op[st.top]!='(') post[j++]=st.op[st.top--]; st.top--; } else if(st.top==-1) st.op[++st.top]=inchar; else { while(precedence(st.op[st.top])>=precedence(inchar)) post[j++]=st.op[st.top--]; st.op[++st.top]=inchar; } } for(;st.top>=0;st.top--) post[j++]=st.op[st.top]; post[j]='\0'; System.out.println("\nThe postfix notation is"+String.valueOf(post).trim());}public static void main(String arg[]){ InfixToPost obj=new InfixToPost(); obj.convert();}} 16. Postfix Evaluation:The postfix expression is evaluated easily by the use of a stack. When a number is seen, it is pushed onto the stack; when an operator is seen, the operator is applied to the two numbers that are popped from the stack and the result is pushed onto the stack.When an expression is given in postfix notation, there is no need to know any precedence rules; this is our obvious advantage.

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 123

Page 36: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures

import java.util.Scanner;import java.lang.Math;public class PostEval{ String exp; float stk[]=new float[20]; int top; public PostEval() { top=-1; } public void getExp() { Scanner sc=new Scanner(System.in); System.out.println("enter a expression"); exp=sc.next(); } public void evaluate() { char op[]={'+','-','*','/','%','^'}; int flag=0,i,j; for(i=0;i<exp.length();i++) { flag=0; for(j=0;j<6;j++) { if(exp.charAt(i)==op[j]) { flag=1; break; } } if(flag==0) { stk[++top]=(float)(exp.charAt(i)-48); } else { float a,b,c=0; b=stk[top--]; a=stk[top--]; switch(exp.charAt(i)) { case '^':c=(float)Math.pow(a, b); break; case '*':c=a*b; break; case '+':c=a+b; break; case '-':c=a-b; break; case '/':c=a/b; break;

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 124

Page 37: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures case '%':c=a%b;break; default:System.out.println("Invalid operator"); } stk[++top]=c; } } System.out.println("The postfix expression is"+exp); System.out.println("Evaluated value is"+stk[0]); } public static void main(String arg[]) { PostEval obj=new PostEval(); obj.getExp(); obj.evaluate(); }}

17. Explain about Queue:A queue is another special kind of list, where items are inserted at one end called the rear and deleted at the other end called the front. Another name for a queue is a “FIFO” or “First-in-first-out” list.

The operations for a queue are analogues to those for a stack, the difference is that the insertions go at the end of the list, rather than the beginning.

Representation of Queue:Let us consider a queue, which can hold maximum of five elements. Initially the queue is empty.

Now, insert 11 to the queue. Then queue status will be:

Next, insert 22 to the queue. Then the queue status is:

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 125

Page 38: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures

Again insert another element 33 to the queue. The status of the queue is:

Now, delete an element. The element deleted is the element at the front of the queue. So the status of the queue is:

Again, delete an element. The element to be deleted is always pointed to by the FRONT pointer. So, 22 is deleted. The queue status is as follows:

Now, insert new elements 44 and 55 into the queue. The queue status is:

Next insert another element, say 66 to the queue. We cannot insert 66 to the queue as the rear crossed the maximum size of the queue (i.e., 5). There will be queue full signal. The queue status is as follows:

18. Representation of a Queue As an array:Queue being a linear list data structure can be represented in various ways, such as arrays and linked lists. Representing a queue as an array has the same defective that are faced by an array i.e., fixed size.

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 126

Page 39: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures import java.util.Scanner;public class QueueAry { final int MAX=5; int Que[]; int front,rear; public QueueAry() { rear=front=-1; Que=new int[MAX]; } public void insert(int data) { if(rear+1==MAX) System.out.println("Queue is overflow"); else { rear++; Que[rear]=data; if(front==-1) front=0; } } public void remove() { if(front==-1) System.out.println("Queue is underflow"); else { System.out.println("Deleted element is:"+Que[front]); front++; if(rear+1==front) rear=front=-1; } } public void display() { if(front==-1) System.out.println("Queue is empty"); else { System.out.print("\nFront-->"); for(int i=front;i<=rear;i++) System.out.print(Que[i]+"-->"); System.out.println("Rear"); } } public static void main(String arg[]) { QueueAry obj=new QueueAry();

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 127

Page 40: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures Scanner sc=new Scanner(System.in); byte ch; do { System.out.println("****************Menu******************"); System.out.print("1.Insert\n2.Remove\nDisplay\n4.Exit\nEnter your choice:"); ch=sc.nextByte(); switch(ch) { case 1:System.out.println("Enter the data to be inserted"); int data=sc.nextInt(); obj.insert(data); break; case 2: obj.remove(); break; case 3: obj.display();break; case 4: System.exit(0); } }while(ch!=4); }}

19. Linked List Implementation of Queue:We can represent a queue as a linked list. In a queue data is deleted from the front end and inserted at the rear end. We can perform similar operations on the two ends of a list. We use two pointers front and rear for our linked queue implementation.

The linked queue looks as shown in figure

import java.util.Scanner;class Node{ int data; Node link;}public class Queuell { Node rear=new Node(); Node front=new Node(); public Queuell() { rear=null; front=null;

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 128

Page 41: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures } public void insert(int data) { Node temp=new Node(); temp.data=data; temp.link=null; if(rear==null) { System.out.println("X"); rear=temp; front=temp; } else { System.out.println("Y"); rear.link=temp; rear=temp; } } public void remove() { Node temp=new Node(); if(front==null) System.out.println("List is underflow"); else { System.out.println("Deleted element is:"+front.data); front=front.link; if(front==null) rear=null; } } public void display() { Node temp=new Node(); if(front==null) System.out.println("List is empty"); else { temp=front; System.out.print("\nFront-->"); while(temp!=null) { System.out.print(temp.data+"-->"); temp=temp.link; } System.out.println("Rear"); } }

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 129

Page 42: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures public static void main(String arg[]) { Queuell obj=new Queuell(); Scanner sc=new Scanner(System.in); byte ch; do { System.out.println("****************Menu******************"); System.out.print("1.Insert\n2.Remove\n3.Display\n4.Exit\nEnter your choice:"); ch=sc.nextByte(); switch(ch) { case 1:System.out.println("Enter the data to be inserted"); int data=sc.nextInt(); obj.insert(data); break; case 2: obj.remove(); break; case 3: obj.display();break; case 4: System.exit(0); } }while(ch!=4); }}

20. Explain about Circular Queues:The queue that we implement using an array suffers from one limitation. In that implementation there is a possibility that the queue is reported as full, even though in actuality there might be empty slots at the beginning of the queue. To overcome this limitation we can implement the queue as circular queue. Here as we go on adding elements to the queue and reach the end of the array, the next element is stored in the first slot of the array provided it is free.Let us consider a circular queue, which can hold maximum (MAX) of six elements. Initially the queue is empty.

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 130

Page 43: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures

Now, insert 11 to the circular queue. Then circular queue status will be:

Insert new elements 22, 33, 44 and 55 into the circular queue. The circular queue status is:

Now, delete an element. The element deleted is the element at the front of the circular queue. So, 11 is deleted. The circular queue status is as follows:

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 131

Page 44: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures

Again, delete an element. The element to be deleted is always pointed to by the FRONT pointer. So, 22 is deleted. The circular queue status is as follows:

Again, insert another element 66 to the circular queue. The status of the circular queue is:

Now, insert new elements 77 and 88 into the circular queue. The circular queue status is:

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 132

Page 45: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures

Now, if we insert an element to the circular queue, as COUNT = MAX we cannot add the element to circular queue. So, the circular queue is full.

Circular Queue Using Array Program:import java.util.Scanner;public class CircularQueAry { final int MAX=5; int front,rear; int CQue[]; public CircularQueAry() { front=rear=-1; CQue=new int[MAX]; } public void insert(int data) { if((rear+1)%MAX==front) System.out.println("Queue is overflow"); else { rear=(rear+1)%MAX; CQue[rear]=data; if(front==-1) front=0; } } public void remove() { if(front==-1) System.out.println("Queue is underflow"); else { System.out.print("\nDeleted element is"+CQue[front]); if(front%MAX!=rear) front=(front+1)%MAX; else

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 133

Page 46: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures rear=front=-1; } } public void display() { if(front==-1) System.out.println("Queue is empty"); else if(front<rear) { System.out.print("\nFront-->"); for(int i=front;i<=rear;i++) System.out.print(CQue[i]+"-->"); System.out.println("Rear"); } else { System.out.print("\nFront-->"); for(int i=front;i<MAX;i++) System.out.print(CQue[i]+"-->"); for(int i=0;i<=rear;i++) System.out.print(CQue[i]+"-->"); System.out.println("Rear"); } } public static void main(String arg[]) { byte t; Scanner sc=new Scanner(System.in); CircularQueAry obj=new CircularQueAry(); do { System.out.print("\n******************Menu*************"); System.out.print("\n\t1.Insert\n\t2.Remove\n\t3.Display\n\t4.Exit\n\tEnter your choice:"); t=sc.nextByte(); switch(t) { case 1: System.out.print("Enter the data to be inserted:"); int data=sc.nextInt(); obj.insert(data);break; case 2: obj.remove(); break; case 3: obj.display(); break; case 4: System.exit(0); } }while(t!=4); }}

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 134

Page 47: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures Implementation of Circular Queue Using Linked Listimport java.util.Scanner;class Node{ int data; Node link;}public class CircularQuell { Node front=new Node(); Node rear=new Node(); public CircularQuell() { front=null; rear=null; } public void insert(int data) { Node temp=new Node(); temp.data=data; temp.link=null; if(rear==null) { front=temp; rear=temp; } else { rear.link=temp; rear=temp; } rear.link=front; } public void remove() { Node temp=new Node(); if(front==null) System.out.println("List is underflow"); else { System.out.println("Deleted data is:"+front.data); if(front!=null) { front=front.link; rear.link=front; } else { front=null;

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 135

Page 48: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures rear=null; } } } public void display() { Node temp=new Node(); temp=front; if(front==null) System.out.println("List is empty"); else { System.out.print("\nFront-->"); do { System.out.print(temp.data+"-->"); temp=temp.link; }while(temp!=front); System.out.println("Rear"); } } public static void main(String arg[]) { CircularQuell obj=new CircularQuell(); Scanner sc=new Scanner(System.in); int data; byte ch; do { System.out.println("*************Menu************"); System.out.print("\t1.Insert\n\t2.Remove\n\t3.Display\n\t4.Exit\n\tEnter your choice:"); ch=sc.nextByte(); switch(ch) { case 1:System.out.println("Enter the data to be inserted:"); data=sc.nextInt(); obj.insert(data); break; case 2: obj.remove(); break; case 3: obj.display(); break; case 4: System.exit(0); } }while(ch!=4); }} 21. Double Ended QueueIn general queue in which we insert items at one end and from which we remove items at the other end. In this section we examine an extension of the queue, which provides a means to insert and remove items at both ends of the queue, but no changes

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 136

Page 49: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures can be made elsewhere in the list. This data structure is a deque. The word deque is an acronym derived from double-ended queue.

There are two variations of deque. They are: Input restricted deque (IRD) Output restricted deque (ORD)

An Input restricted deque is a deque, which allows insertions at one end but allows deletions at both ends of the list.An output restricted deque is a deque, which allows deletions at one end but allows insertions at both ends of the list.

import java.util.Scanner;public class DeQue { int rear,front; final int MAX=5; int DQue[]; public DeQue() { rear=front=-1; DQue=new int[MAX]; } public void insertbeg(int data) { if(front==0 && rear+1==MAX) System.out.println("Queue is overflow"); if(rear==-1) { rear=front=0; DQue[rear]=data; } else if(rear!=MAX-1) { for(int i=rear;i>=front;i--) DQue[i+1]=DQue[i]; DQue[front]=data; rear++; } else {

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 137

Page 50: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures front--; DQue[front]=data; } } public void insertend(int data) { if(front==0 && rear+1==MAX) System.out.println("Queue is overflow"); if(rear==-1) { rear=front=0; DQue[rear]=data; } else if(rear==MAX-1) { for(int i=front;i<=rear;i++) DQue[i-1]=DQue[i]; DQue[rear]=data; front--; } else { rear++; DQue[rear]=data; } } public void removebeg() { if(front==-1) System.out.println("Queue is underflow"); else { System.out.println("Deleted data is"+DQue[front]); front++; if(rear+1==front) front=rear=-1; } } public void removeend() { if(front==-1) System.out.println("Queue is underflow"); else System.out.println("Deleted data is"+DQue[rear]); rear--; if(rear+1==front) front=rear=-1; }public void display()

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 138

Page 51: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures { if(front==-1) System.out.println("Queue is empty"); else { System.out.print("\nFront-->"); for(int i=front;i<=rear;i++) System.out.print(DQue[i]+"-->"); System.out.println("Rear"); }}public static void main(String arg[]){ Scanner sc=new Scanner(System.in); DeQue obj=new DeQue(); byte ch; do { System.out.println("*****************Menu****************"); System.out.print("\n\t1.Insert Begining\n\t2.Insert End\n\t3.Remove Beging\n\t4.Remove End\n\t5.Display\n\t6.Exit\n\tEnter your choice:"); ch=sc.nextByte(); switch(ch) { case 1: System.out.println("Enter the data to be inserted"); int data=sc.nextInt(); obj.insertbeg(data); break; case 2: System.out.println("Enter the data to be inserted"); data=sc.nextInt(); obj.insertend(data); break; case 3: obj.removebeg(); break; case 4: obj.removeend(); break; case 5: obj.display(); break; case 6: System.exit(0); } }while(ch!=6); }}

Input Restriction Queue:import java.util.Scanner;public class InputRes { int rear,front; final int MAX=5; int DQue[]; public InputRes() { rear=front=-1; DQue=new int[MAX];

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 139

Page 52: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures } public void insertend(int data) { if(front==0 && rear+1==MAX) System.out.println("Queue is overflow"); if(rear==-1) { rear=front=0; DQue[rear]=data; } else if(rear==MAX-1) { for(int i=front;i<=rear;i++) DQue[i-1]=DQue[i]; DQue[rear]=data; front--; } else { rear++; DQue[rear]=data; } } public void removebeg() { if(front==-1) System.out.println("Queue is underflow"); else { System.out.println("Deleted data is"+DQue[front]); front++; if(rear+1==front) front=rear=-1; } } public void removeend() { if(front==-1) System.out.println("Queue is underflow"); else System.out.println("Deleted data is"+DQue[rear]); rear--; if(rear+1==front) front=rear=-1; }public void display(){ if(front==-1) System.out.println("Queue is empty");

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 140

Page 53: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures else { System.out.print("\nFront-->"); for(int i=front;i<=rear;i++) System.out.print(DQue[i]+"-->"); System.out.println("Rear"); }}public static void main(String arg[]){ Scanner sc=new Scanner(System.in); DeQue obj=new DeQue(); byte ch; do { System.out.println("*****************Menu****************"); System.out.print("\n\t1.Insert End\n\t2.Remove Beging\n\t3.Remove End\n\t4.Display\n\t5.Exit\n\tEnter your choice:"); ch=sc.nextByte(); switch(ch) { case 1: System.out.println("Enter the data to be inserted"); int data=sc.nextInt(); obj.insertend(data); break; case 2: obj.removebeg(); break; case 3: obj.removeend(); break; case 4: obj.display(); break; case 5: System.exit(0); } }while(ch!=5); }}Output Restriction Queueimport java.util.Scanner;public class OutputRes { int rear,front; final int MAX=5; int DQue[]; public OutputRes() { rear=front=-1; DQue=new int[MAX]; } public void insertbeg(int data) { if(front==0 && rear+1==MAX) System.out.println("Queue is overflow"); if(rear==-1) {

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 141

Page 54: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures rear=front=0; DQue[rear]=data; } else if(rear!=MAX-1) { for(int i=rear;i>=front;i--) DQue[i+1]=DQue[i]; DQue[front]=data; rear++; } else { front--; DQue[front]=data; } } public void insertend(int data) { if(front==0 && rear+1==MAX) System.out.println("Queue is overflow"); if(rear==-1) { rear=front=0; DQue[rear]=data; } else if(rear==MAX-1) { for(int i=front;i<=rear;i++) DQue[i-1]=DQue[i]; DQue[rear]=data; front--; } else { rear++; DQue[rear]=data; } } public void removebeg() { if(front==-1) System.out.println("Queue is underflow"); else { System.out.println("Deleted data is"+DQue[front]); front++; if(rear+1==front) front=rear=-1; }

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 142

Page 55: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures }public void display(){ if(front==-1) System.out.println("Queue is empty"); else { System.out.print("\nFront-->"); for(int i=front;i<=rear;i++) System.out.print(DQue[i]+"-->"); System.out.println("Rear"); }}public static void main(String arg[]){ Scanner sc=new Scanner(System.in); DeQue obj=new DeQue(); byte ch; do { System.out.println("*****************Menu****************"); System.out.print("\n\t1.Insert Begining\n\t2.Insert End\n\t3.Remove Beging\n\t4.Display\n\t5.Exit\n\tEnter your choice:"); ch=sc.nextByte(); switch(ch) { case 1: System.out.println("Enter the data to be inserted"); int data=sc.nextInt(); obj.insertbeg(data); break; case 2: System.out.println("Enter the data to be inserted"); data=sc.nextInt(); obj.insertend(data); break; case 3: obj.removebeg(); break; case 4: obj.display(); break; case 5: System.exit(0); } }while(ch!=5); }}

22. Priority Queue:A priority queue is a collection of elements where the elements are stored according to their priority levels. The order in which the elements should get added or removed is decided by the priority of the element. Following rules are applied to maintain a priority queue.1. the element with a higher priority is processed before any element of lower priority2. if there are elements with the same priority, then the element added first in the queue would be processed.

The best example for priority is job scheduler of operation system.

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 143

Page 56: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures

import java.util.Scanner;class Node{ int data; int pri;}public class PriQueue { final int MAX=5; Node pQue[]; int front,rear; public PriQueue() { pQue=new Node[MAX]; front=-1; rear=-1; } void insert(int item,int pri) { Node temp=new Node(); if(rear+1==MAX) System.out.println("Queue is overflow"); else { temp.data=item; temp.pri=pri; rear++; pQue[rear]=temp; for(int i=rear;i>front&&front!=-1;i--) { if(pQue[i].pri>pQue[i-1].pri) { temp=pQue[i]; pQue[i]=pQue[i-1]; pQue[i-1]=temp; } } if(front==-1) front=0; } } void remove() { if(front==-1) System.out.println("Queue is underflow"); else { System.out.println("Deleted element is"+pQue[front].data);

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 144

Page 57: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures front++; if(rear+1==front) rear=front=-1; } } void display() { if(front==-1) System.out.println("Queue is empty"); else { System.out.print("Front-->"); for(int i=front;i<=rear;i++) System.out.print(pQue[i].data+"-->"); System.out.println("Rear"); } } public static void main(String arg[]) { Scanner sc=new Scanner(System.in); PriQueue obj=new PriQueue(); byte ch; int data,pri; do { System.out.println("*************Menu************"); System.out.print("\t1.Insert\n\t2.Remove\n\t3.Display\n\t4.Exit\n\tEnter your choice:"); ch=sc.nextByte(); switch(ch) { case 1:System.out.println("Enter the data and priority to be inserted"); data=sc.nextInt(); pri=sc.nextInt(); obj.insert(data, pri); break; case 2: obj.remove(); break; case 3: obj.display(); break; case 4: System.exit(0); } }while(ch!=4); }}

23. Explain the tree and tree terminologies?A tree is hierarchical collection of nodes. One of the nodes, known as the root, is at the top of the hierarchy. Each node can have almost one link coming into it. The node where the link originates is called the parent node. The root node has no parent. The links leaving a node (any number of links are allowed) point to child nodes. Trees are

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 145

Page 58: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures recursive structures. Each child node is itself the root of a sub tree. At the bottom of the tree are leaf nodes, which have no children.

Trees represent a special case of more general structures known as graphs. In a graph, there are no restrictions on the number of links that can enter or leave a node, and cycles may be present in the graph. The figure shows a tree and a non-tree.

Many terms are used to describe particular aspects of trees. Path:

A way to move from node to node along the edges that connect them. The resulting sequence of nodes is called a path.

Root: The node at the top of the tree is called the root. There is only one root in a tree. For a collection of nodes and edges to be defined as a tree, there must be one path from the root to any other node.

Parent: Any node except the root has exactly one edge running upward to another node. The node above it is called the parent of the node.

Child: Any node may have one or more lines running downward to other nodes. These nodes below a given node are called its children.

Leaf: A node that has no children is called a leaf node or simply a leaf. There can be only one root in a tree, but there can be many leaves. The node that is not a leaf node is called as internal node

Sub tree: Any node may be considered to be the root of a sub tree, which consists of its children and its children’s children and so on. Any node of a tree, with all of its descendants is a sub tree..

Visiting: A node is visited when program control arrives at the node, usually for the purpose of carrying out some operation on the node, such as checking the value of one of its data fields or displaying it.

Traversing:

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 146

Page 59: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures

To traverse a tree means to visit all the nodes in some specified order. For example, we might visit all the nodes in order of ascending key value.

Level: The level of the node refers to its distance from the root. The root of the tree has level O, and the level of any other node in the tree is one more than the level of its parent. For example, in the binary tree of Figure 7.2.1 node F is at level 2 and node H is at level 3. The maximum number of nodes at any level is 2n.

Keys: One data field in an object is usually designated a key value. This value is used to search for the time or perform other operations on it.

Siblings : The children of the same parent are called siblings.

Height: The maximum level in a tree determines its height. The height of a node in a tree is the length of a longest path from the node to a leaf. The term depth is also used to denote height of the tree. The height of the tree of Figure is 3.

DepthThe depth of a node is the number of nodes along the path from the root to that node. For instance, node ‘C’ in figure has a depth of 1.

24. Explain the binary tree, its properties and types?In general, tree nodes can have any number of children. In a binary tree, each node can have at most two children. A binary tree is either empty or consists of a node called the root together with two binary trees called the left sub tree and the right sub tree. A tree with no nodes is called as a null tree. A binary tree is shown in figure. Binary trees are easy to implement because they have a small, fixed number of child links. Because of this characteristic, binary trees are the mot common types of trees and form the basis of many important data structures. Properties of binary trees:

Some of the important properties of a binary tree are as follows:

1. If h = height of a binary tree, thena. Maximum number of leaves = 2h

b. Maximum number of nodes = 2h + 1 - 12. If a binary tree contains m nodes at level l, it contains at most 2m nodes at

level l + 1. 3. Since a binary tree can contain at most one node at level 0 (the root), it can

contain at most 2l node at level l. 4. The total number of edges in a full binary tree with n node is n - 1.

Strictly Binary tree:

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 147

Page 60: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures

If every non-leaf node in a binary tree has nonempty left and right sub trees, the tree is termed a strictly binary tree. Thus the tree of figure (a) is strictly binary. A strictly binary tree with n leaves always contains 2n - 1 node.

Full Binary tree:

A full binary tree of height h has all its leaves at level h. alternatively; all non leaf nodes of a full binary tree have two children, and the leaf nodes have no children.

A full binary tree with height h has 2h + 1 - 1 nodes. A full binary tree of height h is a strictly binary tree all of whose leaves are at level h. Figure (d) illustrates the full binary tree containing 15 nodes and of height 3.A full binary tree of height h contains 2h leaves and, 2h - 1 non-leaf nodes.

Thus by induction, total number of nodes ( .

For example, a full binary tree of height 3 contains 23+1 – 1 = 15 nodes.

Complete Binary tree:A binary tree with n nodes is said to be complete if it contains all the first n nodes of the above numbering scheme. Figure shows examples of complete and incomplete binary trees.

A complete binary tree of height h looks like a full binary tree down to level h-1, and the level h is filled from left to right.

A complete binary tree with n leaves that is not strictly binary has 2n nodes. For example, the tree of Figure (c) is a complete binary tree having 5 leaves and 10 nodes.

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 148

Page 61: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures

25. Explain the methods of representing the binary tree and its advantages and disadvantages?Data Structures for Binary Trees:

1. Arrays; especially suited for complete and full binary trees. 2. Pointer-based.

Array-based Implementation:

Binary trees can also be stored in arrays, and if the tree is a complete binary tree, this method wastes no space. In this compact arrangement, if a node has an index i, its children are found at indices 2i+1 and 2i+2, while its parent (if any) is found at index floor((i-1)/2) (assuming the root of the tree stored in the array at an index zero).

This method benefits from more compact storage and better locality of reference, particularly during a preorder traversal. However, it requires contiguous memory, expensive to grow and wastes space proportional to 2h - n for a tree of height h with n nodes.

Linked Representation (Pointer based):

Array representation is good for complete binary tree, but it is wasteful for many other binary trees. The representation suffers from insertion and deletion of node from the middle of the tree, as it requires the moment of potentially many nodes to reflect

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 149

Page 62: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures the change in level number of this node. To overcome this difficulty we represent the binary tree in linked representation.In linked representation each node in a binary has three fields, the left child field denoted as LeftChild, data field denoted as data and the right child field denoted as RightChild. If any sub-tree is empty then the corresponding pointer’s LeftChild and RightChild will store a NULL value. If the tree itself is empty the root pointer will store a NULL value.

The advantage of using linked representation of binary tree is that: Insertion and deletion involve no data movement and no movement of

nodes except the rearrangement of pointers.The disadvantages of linked representation of binary tree includes:

Given a node structure, it is difficult to determine its parent node. Memory spaces are wasted for storing NULL pointers for the nodes, which

have no sub trees. The structure definition, node representation empty binary tree is shown in figure and the linked representation of binary tree using this node structure is given in figure

26.Program for Array representation of binary tree?import java.util.Scanner;import java.lang.Math;public class BTreeAry { final int H=2; int a[]; public BTreeAry() { a=new int[(int)Math.pow(2, H+1)-1]; } void insert(int data,int ind) { Scanner sc=new Scanner(System.in); int temp,i; if(ind==0) a[ind]=data; if(data!=-1) {

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 150

Page 63: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures System.out.println("Enter the left child of:"+data); temp=sc.nextInt(); i=2*ind+1; a[i]=temp; insert(temp,i); System.out.println("Enter the right child of:"+data); temp=sc.nextInt(); i=2*ind+2; a[i]=temp; insert(temp,i); } } void display() { System.out.print("\nRoot-->"); for(int i=0;i<Math.pow(2,H+1)-1;i++) System.out.print(a[i]+"\t"); } void remove() { boolean del=false; System.out.print("Deleted element is:"); for(int i=(int)Math.pow(2, H+1)-2;i>=0;i--) if(a[i]!=-1) { System.out.println("Deleted element is"+a[i]); del=true; a[i]=-1; break; } if(del==false) System.out.println("Tree is empty"); } public static void main(String arg[]) { Scanner sc=new Scanner(System.in); byte ch; BTreeAry obj=new BTreeAry(); do { System.out.println("\n************Menu**********"); System.out.print("\t1.Create\n\t2.Print Tree\n\t3.Remove\n\t4.Exit\n\tEnter your choice:"); ch=sc.nextByte(); switch(ch) { case 1: System.out.println("Enter the root data"); int data=sc.nextInt(); obj.insert(data,0); break;

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 151

Page 64: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures case 2: System.out.print("\nPrint Tree"); obj.display(); break; case 3: obj.remove(); break; case 4: System.exit(0); } }while(ch!=4); }

}

27.Write a program for pointer representation of binary tree?import java.util.Scanner;class Node{ Node left; int data; Node right;}public class BTreell { int nodectr=0; Node root; Node Que[]; public BTreell() { root=new Node(); root=null; Que=new Node[50]; } Node getNode() { Scanner sc=new Scanner(System.in); Node temp=new Node(); System.out.println("Enter the data"); temp.data=sc.nextInt(); temp.left=null; temp.right=null; return temp; } void create(Node root) { Scanner sc=new Scanner(System.in); char ch; if(root!=null) { System.out.println("Does the "+root.data+" has a left child"); ch=sc.nextLine().charAt(0); if(ch=='y'||ch=='Y') {

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 152

Page 65: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures root.left=getNode(); create(root.left); } System.out.println("Does the "+root.data+" has a right child"); ch=sc.nextLine().charAt(0); if(ch=='y'||ch=='Y') { root.right=getNode(); create(root.right); } } } void preOrder(Node root) { if(root!=null) { System.out.print(root.data+"\t"); preOrder(root.left); preOrder(root.right); } } void postOrder(Node root) { if(root!=null) { postOrder(root.left); postOrder(root.right); System.out.print(root.data+"\t"); } } void inOrder(Node root) { if(root!=null) { inOrder(root.left); System.out.print(root.data+"\t"); inOrder(root.right); } } void printleaf(Node root) { if(root!=null) { if(root.left==null && root.right==null) System.out.print(root.data+"\t"); printleaf(root.left); printleaf(root.right); } }

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 153

Page 66: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures void print(Node root,int line) { if(root!=null) { print(root.right,line+1); System.out.println(); for(int i=0;i<line;i++) System.out.print(" "); System.out.print(root.data); print(root.left,line+1); } } int max(int a,int b) { return a>b?a:b; } int height(Node root) { if(root==null) return -1; else return(1+max(height(root.left),height(root.right))); } void makeQueue(Node root,int ind) { if(root!=null) { nodectr++; Que[ind]=root; makeQueue(root.left,2*ind+1); makeQueue(root.right,2*ind+2); } } void remove(Node root) { int ind,par; if(root==null) { System.out.println("Tree is empty"); } else { nodectr=0; makeQueue(root,0); ind=nodectr-1; System.out.println("Node Counter:"+nodectr); par=(ind-1)/2; System.out.println("Deleted node is"+Que[ind].data); Que[ind]=null;

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 154

Page 67: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures if(par*2+1==ind) Que[par].left=null; else Que[par].right=null; } } public static void main(String arg[]) { Scanner sc=new Scanner(System.in); byte ch; BTreell obj=new BTreell(); do { System.out.println("\n************Menu**********"); System.out.print("\t1.Create\n\t2.PreOrder\n\t3.Inorder\n\t4.PostOrder\n\t5.PrintLeaf\n\t6.Print Tree\n\t7.Height\n\t8.Remove\n\t9.Exit\n\tEnter your choice:"); ch=sc.nextByte(); switch(ch) { case 1: if(obj.root==null) { obj.root=obj.getNode(); obj.create(obj.root); } else System.out.println("Tree is already created"); break; case 2: System.out.print("\nPreOrder Traversal:"); obj.preOrder(obj.root); break; case 3: System.out.print("\nInorder Traversal:"); obj.inOrder(obj.root); break; case 4: System.out.print("Postorder Traversal:"); obj.postOrder(obj.root); break; case 5: System.out.print("Leaf Nodes are:"); obj.printleaf(obj.root); break; case 6: System.out.print("\nPrint Tree"); obj.print(obj.root, 0); break; case 7: System.out.print("\nHeight of tree is:"+ obj.height(obj.root)); break; case 8: obj.remove(obj.root); break; case 9: System.exit(0); } }while(ch!=9); }}

28. Explain about Graphs:

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 155

Page 68: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures Graph G is a pair (V, E), where V is a finite set of vertices and E is a finite set of edges. We will often denote n = |V|, e = |E|.A graph is generally displayed as figure , in which the vertices are represented by circles and the edges by lines. An edge with an orientation (i.e., arrow head) is a directed edge, while an edge with no orientation is our undirected edge. If all the edges in a graph are undirected, then the graph is an undirected graph. The graph of figures (a) is undirected graphs. If all the edges are directed; then the graph is a directed graph. The graph of figure (b) is a directed graph. A directed graph is also called as digraph. A graph G is connected if and only if there is a simple path between any two nodes in G. A graph G is said to be complete if every node a in G is adjacent to every other node v in G. A complete graph with n nodes will have n(n-1)/2 edges. For example, Figure (a) and figure (d) are complete graphs.A directed graph G is said to be connected, or strongly connected, if for each pair u, v for nodes in G there is a path from u to v and there is a path from v to u. On the other hand, G is said to be unilaterally connected if for any pair u, v of nodes in G there is a path from u to v or a path from v to u. For example, the digraph shown in figure (e) is strongly connected.We can assign weight function to the edges: wG (e) is a weight of edge e E. The graph which has such function assigned is called weighted graph.

The number of incoming edges to a vertex v is called in–degree of the vertex (denote indeg(v)). The number of outgoing edges from a vertex is called out-degree (denote outdeg(v)). For example, let us consider the digraph shown in figure (f),indegree(v1) = 2 outdegree(v1) = 1indegree(v2) = 2 outdegree(v2) = 0

A path is a sequence of vertices (v1, v2, . . . . . . , vk), where for all i, (vi, vi+1) E. A path is simple if all vertices in the path are distinct. If there a path containing one or more edges which starts from a vertex Vi and terminates into the same vertex then the path is known as a cycle. For example, there is a cycle in figure (a), figure (c) and figure (d).

If a graph (digraph) does not have any cycle then it is called acyclic graph. For example, the graphs of figure (f) and figure (g) are acyclic graphs.

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 156

Page 69: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures A graph G’ = (V’, E’) is a sub-graph of graph G = (V, E) iff V’ V and E’ E.

29.What are the different representing the graph?Representation of Graphs:There are two ways of representing digraphs. They are:

Adjacency matrix. Adjacency List.

Adjacency matrix:In this representation, the adjacency matrix of a graph G is a two dimensional n x n matrix, say A = (ai,j), where

The matrix is symmetric in case of undirected graph, while it may be asymmetric if the graph is directed. This matrix is also called as Boolean matrix or bit matrix.

Figure (b) shows the adjacency matrix representation of the graph G1 shown in figure (a). The adjacency matrix is also useful to store multigraph as well as weighted graph. In case of multigraph representation, instead of entry 0 or 1, the entry will be between number of edges between two vertices.

In case of weighted graph, the entries are weights of the edges between the vertices. The adjacency matrix for a weighted graph is called as cost adjacency matrix. Figure (b) shows the cost adjacency matrix representation of the graph G2 shown in figure (a).

Adjacency List: In this representation, the n rows of the adjacency matrix are represented as n linked lists. An array Adj[1, 2, . . . . . n] of pointers where for 1 < v < n, Adj[v] points to a linked list containing the vertices which are adjacent to v (i.e. the vertices that can be reached from v by a single edge). If the edges have weights then these weights may

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 157

1 2 3 4 51 0 1 1 0 12 0 0 1 1 13 0 0 0 1 04 0 0 0 0 05 0 0 1 1 0

A B C D E F GA 0 3 6 B 3 0 2 4 C 6 2 0 1 4 2 D 4 1 0 2 4E 4 2 0 2 1F 2 2 0 1G 4 1 1 0

(b)

G2:

(b)

Page 70: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures also be stored in the linked list elements. For the graph G in figure (a), the adjacency list in shown in figure (b).

30. Explain BFS and DFS?Traversing a Graph:

Many graph algorithms require one to systematically examine the nodes and edges of a graph G. There are two standard ways to do this. They are:

Breadth first traversal (BFT) Depth first traversal (DFT)

The BFT will use a queue as an auxiliary structure to hold nodes for future processing and the DFT will use a STACK.

During the execution of these algorithms, each node N of G will be in one of three states, called the status of N, as follows:

1. STATUS = 1 (Ready state): The initial state of the node N.

2. STATUS = 2 (Waiting state): The node N is on the QUEUE or STACK, waiting to be processed.

3. STATUS = 3 (Processed state): The node N has been processed.

Both BFS and DFS impose a tree (the BFS/DFS tree) on the structure of graph. So, we can compute a spanning tree in a graph. The computed spanning tree is not a minimum spanning tree. The spanning trees obtained using depth first searches are called depth first spanning trees. The spanning trees obtained using breadth first searches are called Breadth first spanning trees.

Breadth first search and traversal:The general idea behind a breadth first traversal beginning at a starting node A is as follows. First we examine the starting node A. Then we examine all the neighbors of A. Then we examine all the neighbors of neighbors of A. And so on. We need to keep track of the neighbors of a node, and we need to guarantee that no node is processed more than once. This is accomplished by using a QUEUE to hold nodes that are

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 158

Page 71: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures waiting to be processed, and by using a field STATUS that tells us the current status of any node. The spanning trees obtained using BFS are called Breadth first spanning trees.

Breadth first traversal algorithm on graph G is as follows:This algorithm executes a BFT on graph G beginning at a starting node A.

Initialize all nodes to the ready state (STATUS = 1).

1. Put the starting node A in QUEUE and change its status to the waiting state (STATUS = 2).

2. Repeat the following steps until QUEUE is empty:

a. Remove the front node N of QUEUE. Process N and change the status of N to the processed state (STATUS = 3).

b. Add to the rear of QUEUE all the neighbors of N that are in the ready state (STATUS = 1), and change their status to the waiting state (STATUS = 2).

3. Exit. Breadth first searchimport java.util.Scanner;public class BFS { final int N=9; char vertex[],Que[],adjlist[][]; byte status[]; int t,f=0,r=0,i,j; public BFS() { status=new byte[N]; Que=new char[N]; vertex=new char[N]; adjlist=new char[N][N]; } void insert() { Scanner sc=new Scanner(System.in); for(int i=0;i<N;i++) { System.out.println("Enter "+(i+1)+" the vertex"); vertex[i]=sc.nextLine().charAt(0); } sc.reset(); System.out.println("Enter the adjacent members for the vertex"); for(i=0;i<N;i++) { System.out.println("How many adjacent members for "+vertex[i]);

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 159

Page 72: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures t=sc.nextInt(); for(j=0;j<t;j++) { adjlist[i][j]=sc.next().charAt(0); } adjlist[i][j]='?'; } } void calculate() { int i,j; for(i=0;i<N;i++) status[i]=0; int t=N-1,p=0,vno=0; char v; Que[r++]=vertex[0]; status[0]=1; System.out.println("Removed element is"+Que[f++]); status[0]=2; while(t!=0) { for(i=0;adjlist[p][i]!='?';i++) { v=adjlist[p][i]; for(j=0;j<N;j++) if(vertex[j]==v) { vno=j; break; } if(status[vno]==0) Que[r++]=v; status[vno]=1; } v=Que[f++]; for(j=0;j<N;j++) if(vertex[j]==v) { p=j; break; } System.out.println("Removed element is"+v); status[p]=2; t--; } } public static void main(String arg[]) { BFS obj=new BFS();

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 160

Page 73: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures obj.insert(); obj.calculate(); }}Depth first search of undirected graph proceeds as follows: First we examine the starting node V. Next an unvisited vertex 'W' adjacent to 'V' is selected and a depth first search from 'W' is initiated. When a vertex 'U' is reached such that all its adjacent vertices have been visited, we back up to the last vertex visited, which has an unvisited vertex 'W' adjacent to it and initiate a depth first search from W. The search terminates when no unvisited vertex can be reached from any of the visited ones.

This algorithm is similar to the inorder traversal of binary tree. DFT algorithm is similar to BFT except now use a STACK instead of the QUEUE. Again field STATUS is used to tell us the current status of a node.

The algorithm for depth first traversal on a graph G is as follows.

This algorithm executes a DFT on graph G beginning at a starting node A.

1. Initialize all nodes to the ready state (STATUS = 1).2. Push the starting node A into STACK and change its status to the waiting state

(STATUS = 2).3. Repeat the following steps until STACK is empty:

a. Pop the top node N from STACK. Process N and change the status of N to the processed state (STATUS = 3).

b. Push all the neighbors of N that are in the ready state (STATUS = 1), and change their status to the waiting state (STATUS = 2).

4. Exit.

Depth First Searchimport java.util.Scanner;public class DFS { final int N=9; char vertex[],Stk[],adjlist[][]; byte status[]; int t,top=0,i,j; public DFS() { status=new byte[N]; Stk=new char[N]; vertex=new char[N]; adjlist=new char[N][N]; } void insert() { Scanner sc=new Scanner(System.in);

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 161

Page 74: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures for(int i=0;i<N;i++) { System.out.println("Enter "+(i+1)+" the vertex"); vertex[i]=sc.nextLine().charAt(0); } sc.reset(); System.out.println("Enter the adjacent members for the vertex"); for(i=0;i<N;i++) { System.out.println("How many adjacent members for "+vertex[i]); t=sc.nextInt(); for(j=0;j<t;j++) { adjlist[i][j]=sc.next().charAt(0); } adjlist[i][j]='?'; } } void calculate() { int i,j; for(i=0;i<N;i++) status[i]=0; int t=N-1,p=0,vno=0; char v; Stk[top++]=vertex[0]; status[0]=1; System.out.println("Popped element is"+Stk[--top]); status[0]=2; while(t!=0) { for(i=0;adjlist[p][i]!='?';i++) { v=adjlist[p][i]; for(j=0;j<N;j++) if(vertex[j]==v) { vno=j; break; } if(status[vno]==0) Stk[top++]=v; status[vno]=1; } v=Stk[--top]; for(j=0;j<N;j++) if(vertex[j]==v) { p=j;

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 162

Page 75: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures break; } System.out.println("Removed element is"+v); status[p]=2; t--; } } public static void main(String arg[]) { DFS obj=new DFS(); obj.insert(); obj.calculate(); }}

Example 1:Consider the graph shown below. Traverse the graph shown below in breadth first order and depth first order.

Breadth-first search and traversal:For the above graph the breadth first traversal sequence is: A F C B D E G J K.

Depth-first search and traversal:For the above graph the depth first traversal sequence is: A F D J K G E C B.

31. Explain about Minimum Spanning Tree:A spanning tree of a graph is an undirected tree consisiting of only those edges that are necessary to connect all the vertices in the original path. A spanning tree has a property that for any pair of vertices there exists only one path between them, and the insetion of any edge to a spanning tree form a unique cycle.

When we consider the path, we try to have minimum number of traces to cover all the nodes. The result would be a graph with the minimum number of edges necessary to

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 163

Node Adjacency List

A F, C, B

B A, C, G

C A, B, D, E, F, G

D C, F, E, J

E C, D, G, J, K

F A, C, D

G B, C, E, K

J D, E, K

K E, G, J

Adjacency list for graph G

Page 76: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures connect the vertices. The arithmetically inclined will note that the number of edges E in a minimum spanning tree is always one less than the number of vertices V: E = V – 1

Program for Minimum Spanning Treeimport java.util.Scanner;public class MST { final int N=5; char vertex[],Stk[],adjlist[][]; byte status[]; int t,top=0,i,j; public MST() { status=new byte[N]; Stk=new char[N]; vertex=new char[N]; adjlist=new char[N][N]; } void insert() { Scanner sc=new Scanner(System.in); for(int i=0;i<N;i++) { System.out.println("Enter "+(i+1)+" the vertex"); vertex[i]=sc.nextLine().charAt(0); } sc.reset(); System.out.println("Enter the adjacent members for the vertex"); for(i=0;i<N;i++) { System.out.println("How many adjacent members for "+vertex[i]); t=sc.nextInt(); for(j=0;j<t;j++) { adjlist[i][j]=sc.next().charAt(0); } adjlist[i][j]='?'; } } void calculate() { int i,j; for(i=0;i<N;i++) status[i]=0; int t=N,p=0,vno=0; char v; Stk[top++]=vertex[0]; status[0]=1;

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 164

Page 77: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures while(t!=0) { status[0]=2; char ch=Stk[top]; for(i=0;adjlist[p][i]!='?';i++) { v=adjlist[p][i]; for(j=0;j<N;j++) if(vertex[j]==v) { vno=j; break; } if(status[vno]==0) Stk[top++]=v; status[vno]=1; } System.out.print(ch); System.out.print(Stk[top-1]); v=Stk[--top]; for(j=0;j<N;j++) if(vertex[j]==v) { p=j; break; } status[p]=2; t--; System.out.print(" "); } } public static void main(String arg[]) { MST obj=new MST(); obj.insert(); System.out.println("Minimum Spanning Team:"); obj.calculate(); }}

32.Explain about Topological sorting:Topological sorting is an ordering of vertices of a graph, such that if there is a path from u to v in the graph then u appears before v in the ordering. For example, in the graph as shown in figure, the topological sorting of all vertices is A-B-C-D.It is clear that a topological ordering is not possible if the graph has a cycle, since for two vertices u and v on the cycle, u precedes v and v precedes u. It also can be proved that, for a directed acyclic graph, there exists a topological ordering of vertices.

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 165

Page 78: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures The simple process of topological ordering is to find out any vertex with indegree zero, that is, a vertex without any predecessor. We can then add this vertex in a ordering set and remove it along with its edges from the graph. Then we repeat the same strategy on the remaining graph until it is empty.

import java.util.Scanner;public class TopoSort { final int N=7; char vertex[],sort[]; byte adjlist[][]; boolean status[]; public TopoSort() { status=new boolean[N]; vertex=new char[N]; adjlist=new byte[N][N]; sort=new char[N]; } void insert() { int i,j; Scanner sc=new Scanner(System.in); for(i=0;i<N;i++) { System.out.println("Enter "+(i+1)+" the vertex"); vertex[i]=sc.nextLine().charAt(0); } sc.reset(); for(i=0;i<N;i++) { System.out.println("enter the adjacent list for "+vertex[i]); for(j=0;j<N;j++) { adjlist[i][j]=sc.nextByte(); } } for(i=0;i<N;i++) { for(j=0;j<N;j++) System.out.print(adjlist[i][j]+"\t"); System.out.println(); } } void calculate() { int i,j; for(i=0;i<N;i++)

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 166

Page 79: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures status[i]=false; int k=0; boolean zeroind=false; boolean flag=true; while(flag) { zeroind=true; for(i=0;i<N;i++) { if(status[i]==false) { zeroind=true; for(j=0;j<N;j++) { if(adjlist[i][j]>0) { zeroind=false; break; } } if(zeroind) { status[i]=true; sort[k]=vertex[i]; k++; for(j=0;j<N;j++) { adjlist[i][j]=-1; adjlist[j][i]=-1; } break; } } } if(i==N && zeroind==false) { flag=false; System.out.println("Graph is not a acyclic"); return; } if(k==N) { System.out.println("Sorted Order is"); for(i=0;i<N;i++) System.out.print(sort[i]+"\t"); return; } } }

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 167

Page 80: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures public static void main(String arg[]) { TopoSort obj=new TopoSort(); obj.insert(); obj.calculate(); }}Short Answers Questions:1. Data Structure: A data structure is a particular way of storing and organizing data in a computer so that it can be used efficiently. Different kinds of data structures are suited to different kinds of applications, and some are highly specialized to certain tasks. Some formal design methods and programming languages emphasize data structures, rather than algorithms, as the key organizing factor is software design.2. Primitive Data Structure: These are the data structures which are directly supported by the languages ,i.e., any operation will be directly performed in these data items. Few examples for primitive data structures are integers, real numbers, characters,etc. Operations on primitive types to be the fastest language constructs there are. 3. Non Primitive Data Structure: These data structures do not allow any specific instruction to be performed on the data item directly. The best example of this data structure is set of complex numbers. A non-primitive data structure is built out of primitive data structures liked together in meaningful ways, such as a binary search tree, AVL tree, Hashtable etc. 4. Linear Data Structure: These data structures involves arranging the elements on a linear fashion5. Non Linear Data Structure: 6. Linked List: A linked lists refers to a linear collection of data items. It is a flexible data structure, i.e, items can be inserted or deleted dynamically. The main operations on linked lists are insertion of a new element, deletion of a particular element & accessing a particular element. Linked lists & Arrays resemble as same, but a linked list is a dynamic data structure where as an array is static data structure7. Stack: A stack is a list of elements in which an element may be inserted or deleted only at one end, called the top of the stack. Stacks are sometimes known as LIFO (last in, first out) lists. As the items can be added or removed only from the top i.e. the last item to be added to a stack is the first item to be removed.8. Queue: A queue is another special kind of list, where items are inserted at one end called the rear and deleted at the other end called the front. Another name for a queue is a “FIFO” or “First-in-first-out” list. The operations for a queue are analogues to those for a stack, the difference is that the insertions go at the end of the list, rather than the beginning.9. Tree: A tree is hierarchical collection of nodes. One of the nodes, known as the root, is at the top of the hierarchy. Each node can have almost one link coming into it. The node where the link originates is called the parent node. The root node has no parent. The links leaving a node (any number of links are allowed) point to child nodes. Trees are recursive structures. Each child node is itself the root of a subtree. At the bottom of the tree are leaf nodes, which have no children.10. Graph: Graph is a data structure mainly used in the applications such as finding shortest routes/paths analysis of electrical circuits chemical compounds etc ,this data structure consists of a finite number of non-empty set of vertices as well as edges

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 168

Page 81: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures 11. Single Linked List: : a single linked list is represented expanding each node to a link to the next node as shown below

First Last

In the above figure ‘first’ is a variable which contains an address which gives the location of the first node. Each node is divided into two fields. The first field known ‘as information field, gives the information of the element and the second field known as link field, contains the address of the next node.

12. Circular Single Linked List: The circular linked list suppresses the limitations of moving is only one direction. This is done by providing a link from the last node to the first node.

First` LastThis type of listing is known as circular linked listing. In this type of list, we can move in one direction only but can come to the beginning of the node unlike in the case of single linked list

13. Double Linked List: In doubly linked list, one can move in both direction. Since each node contains two link components instead of one, it requires more memory. This doubly linked list would be as follows:

First LastThe link which denotes the previous node is called left link and link which denotes a successor node is called right link. Thus moving in either directions is possible through a doubly linked list. 14. Applications of Stack:

1. 1.Stack is used by compilers to check for balancing of parentheses, brackets and braces.

2. Stack is used to evaluate a postfix expression.3. Stack is used to convert an infix expression into postfix/prefix form.4. In recursion, all intermediate arguments and return values are stored on the

processor’s stack.5. During a function call the return address and arguments are pushed onto a

stack and on return they are popped off.6. Depth first search uses a stack data structure to find an element from a graph.

15. Expression Evaluation: The place where stacks are frequently used is in evaluation of arithmetic expression. The notation are prefix, infix and postfix notations. The fundamental property of polish notation is that the order in which the

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 169

Page 82: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures operations are to be performed is completely determined by the positions of the operators and operands in the expression.

a) Prefix Notation: Operator is placed before the operandb) Infix Notation: Operator is placed inbetween the operandc) Postfix Notation: Operator is placed after the operand.’

16. Circular Queue: The queue that we implement using an array suffers from one limitation. In that implementation there is a possibility that the queue is reported as full, even though in actuality there might be empty slots at the beginning of the queue. To overcome this limitation we can implement the queue as circular queue. Here as we go on adding elements to the queue and reach the end of the array, the next element is stored in the first slot of the array provided it is free17. Double Ended Queue: In general queue in which we insert items at one end and from which we remove items at the other end. Deque an extension of the queue, which provides a means to insert and remove items at both ends of the queue, but no changes can be made elsewhere in the list. This data structure is a deque. The word deque is an acronym derived from double-ended queue.18. Input Restriction Queue: In general queue in which we insert items at one end and from which we remove items at the other end. Input restriction queue is an extension of the queue, but has a restriction that insertion should takes place only at one end, but where as the deletion can take place at both end. 19. Output Restriction Queue: In general queue in which we insert items at one end and from which we remove items at the other end. Input restriction queue is an extension of the queue, but has a restriction that insertion can takes place at both end, but where as the deletion should take place only one end. 20. Priority Queue: A priority queue is a collection of elements where the elements are stored according to their priority levels. The order in which the elements should get added or removed is decided by the priority of the element. Following rules are applied to maintain a priority queue.1. the element with a higher priority is processed before any element of lower priority2. if there are elements with the same priority, then the element added first in the queue would be processed.21. Binary Tree: In general, tree nodes can have any number of children. In a binary tree, each node can have at most two children. A binary tree is either empty or consists of a node called the root together with two binary trees called the left subtree and the right subtree. A tree with no nodes is called as a null tree22. Level : The level of the node refers to its distance from the root. The root of the tree has level O, and the level of any other node in the tree is one more than the level of its parent. For example, in the binary tree of Figure 7.2.1 node F is at level 2 and node H is at level 3. The maximum number of nodes at any level is 2n.23. Height and Depth: Height:

The maximum level in a tree determines its height. The height of a node in a tree is the length of a longest path from the node to a leaf. The term depth is also used to denote height of the tree. The height of the tree of Figure is 3.

DepthThe depth of a node is the number of nodes along the path from the root to that node. For instance, node ‘C’ in figure has a depth of 1.

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 170

Page 83: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures 24. Full Binary Tree: A full binary tree of height h has all its leaves at level h. Alternatively; All non leaf nodes of a full binary tree have two children, and the leaf nodes have no children. A full binary tree with height h has 2h + 1 - 1 nodes. A full binary tree of height h is a strictly binary tree all of whose leaves are at level h. A full binary tree of height h contains 2h leaves and, 2h - 1 non-leaf nodes.25. Complete Binary Tree: A binary tree with n nodes is said to be complete if it contains all the first n nodes of the above numbering scheme. Figure shows examples of complete and incomplete binary trees. A complete binary tree of height h looks like a full binary tree down to level h-1, and the level h is filled from left to right. A complete binary tree with n leaves that is not strictly binary has 2n nodes.26. Tree Traversal: A tree traversal is a method of visiting every node in the tree. By visit, we mean that same type of operation is performed. For example, you may wish to print the contents of the nodes. Three basic traversals use commonly used. There are four common ways to traverse a binary tree:

1. Preorder2. Inorder 3. Postorder

In the first three traversal methods, the left subtree of a node is traversed before the right subtree. The difference among them comes from the difference in the time at which a root node is visited27. Preorder: In a preorder traversal, each root node is visited before its left and right subtrees are traversed. Preorder search is also called backtracking. The steps for traversing a binary tree in preorder traversal are:

1. Visit the root.2. Visit the left subtree, using preorder.3. Visit the right subtree, using preorder.

28. Inorder: In the case of inorder traversal, the root of each subtree is visited after its left subtree has been traversed but before the traversal of its right subtree begins. The steps for traversing a binary tree in inorder traversal are:

1. Visit the left subtree, using inorder.2. Visit the root.3. Visit the right subtree, using inorder.

29. Postorder: In a postorder traversal, each root is visited after its left and right subtrees have been traversed. The steps for traversing a binary tree in postorder traversal are:

1. Visit the left subtree, using postorder.2. Visit the right subtree, using postorder3. Visit the root.

30. Adjacent Matrix: In this representation, the adjacency matrix of a graph G is a two dimensional n x n matrix, say A = (ai,j), where

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 171

Page 84: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures The matrix is symmetric in case of undirected graph, while it may be asymmetric if the graph is directed. This matrix is also called as Boolean matrix or bit matrix.

31. Adjacent List: In this representation, the n rows of the adjacency matrix are represented as n linked lists. An array Adj[1, 2, . . . . . n] of pointers where for 1 < v < n, Adj[v] points to a linked list containing the vertices which are adjacent to v (i.e. the vertices that can be reached from v by a single edge). If the edges have weights then these weights may also be stored in the linked list elements. For the graph G in figure (a), the adjacency list in shown in figure (b).

32. Breath First Search: The general idea behind a breadth first traversal beginning at a starting node A is as follows. First we examine the starting node A. Then we examine all the neighbors of A. Then we examine all the neighbors of neighbors of A. And so on. We need to keep track of the neighbors of a node, and we need to guarantee that no node is processed more than once. This is accomplished by using a QUEUE to hold nodes that are waiting to be processed, and by using a field STATUS that tells us the current status of any node. The spanning trees obtained using BFS are called Breadth first spanning trees. 33. Depth First Search: Depth first search of undirected graph proceeds as follows: First we examine the starting node V. Next an unvisited vertex 'W' adjacent to 'V' is selected and a depth first search from 'W' is initiated. When a vertex 'U' is reached such that all its adjacent vertices have been visited, we back up to the last vertex visited, which has an unvisited vertex 'W' adjacent to it and initiate a depth first search from W. The search terminates when no unvisited vertex can be reached from any of the visited ones. 34. Minimum Spanning Tree: A spanning tree of a graph is an undirected tree consisiting of only those edges that are necessary to connect all the vertices in the original path. A spanning tree has a property that for any pair of vertices there exists only one path between them, and the insetion of any edge to a spanning tree form a unique cycle.

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 172

1 2 3 4 51 0 1 1 0 12 0 0 1 1 13 0 0 0 1 04 0 0 0 0 05 0 0 1 1 0

Page 85: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures 35. Directed Graph: A directed graph is also called as digraph. In a graph G, such that, G = <V,E> where V is the set of all vertices and E is the set of ordered pair of elements from V. Here, if an order pair (vi,vj) is in E then there is an edge directed from vi to vj. i.e., the edges need to have a direction. In a directed graph we can proceed only one way along an edge. The arrows in the figure show the direction of the edges.

36. Undirected Graph: A undirected graph is also simple called as graph. In a graph G, such that, G = <V,E> where V is the set of all vertices and E is the set of ordered pair of elements from V. In this case pair (vi,vj) is unordered, that is (vi,vj) and (vj,vi) are the same edges. That means that the edges don’t have a direction, we can go either way on them.

37. Weighted Graph: A graph or digraph is termed as weighted graph if all the edges in it are labeled with some weights i.e., a number that can represent the physical distance between two vertices, or the time it takes to get from one vertex to another, or how much it costs to travel from vertex to vertex. Such graphs are called weighted graph.

38. Explain the types of Queues?Types of Queues:

1. Normal Queue2. Circular Queue3. Double Ended Queue

3.1 Input Restriction3.2 Output Restriction

priority QueuePaper - IIPaper - II

Object Oriented Programming With Java and Data StructuresObject Oriented Programming With Java and Data StructuresS.V.University – Unit VS.V.University – Unit V

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 173

Page 86: UNIT 5.doc

Unit V Object Oriented Programming in Java and Data Structures

Sept– 11

1. Explain about quick sort with example.

2. Explain in detail minimum spanning tree.

3. Define stack. Write about application of stack

March/April - 2011

1. Explain about selection sort and bubble sort with an example

2. Explain in detail minimum spanning tree.

3. Define linked list? Write a program to insert, delete an element in a double

linked list.

Sept– 10

1. Define linked list? Write a program to insert, delete an element in a single

linked list.

2. Explain about quick sort with example.

3. Write a program in java to construct binary search tree and implement tree

traversal techniques.

March/April - 20101. Explain about insertion sort with an example

2. Define stack. Write about application of stack.

3. Explain in detail Minimum spanning tree

Gayatri Degree & PG College, 164,Prakasam Road,Tpt II B.Sc 174


Recommended