0% found this document useful (0 votes)
98 views96 pages

Sem-Iv Recordmodifing

The document discusses implementing linked lists in Java. It provides: 1) An overview of singly linked lists, including their structure where each node stores data and a pointer to the next node. It shows pictorial examples of inserting and deleting a node from a singly linked list. 2) An algorithm for common singly linked list operations like adding and removing from the start/end and getting the size or an element at an index. 3) Java code to implement a singly linked list with these operations. 4) An overview of doubly linked lists where each node stores pointers to both the next and previous nodes, allowing traversal in both directions. It shows examples of inserting and deleting from a doubly linked list.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
98 views96 pages

Sem-Iv Recordmodifing

The document discusses implementing linked lists in Java. It provides: 1) An overview of singly linked lists, including their structure where each node stores data and a pointer to the next node. It shows pictorial examples of inserting and deleting a node from a singly linked list. 2) An algorithm for common singly linked list operations like adding and removing from the start/end and getting the size or an element at an index. 3) Java code to implement a singly linked list with these operations. 4) An overview of doubly linked lists where each node stores pointers to both the next and previous nodes, allowing traversal in both directions. It shows examples of inserting and deleting from a doubly linked list.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 96

DATA STRUCTURES USING JAVA SEMESTER-IV

Program - 1
1. Write a program to implement the linked list operations

(a) Single Linked:

Singly Linked Lists are a type of data structure. It is a type of list. In a singly
linked list each node in the list stores the contents of the node and a pointer or
reference to the next node in the list. It does not store any pointer or reference to
the previous node. It is called a singly linked list because each node only has a single
link to another node. To store a single linked list, you only need to store a reference
or pointer to the first node in that list. The last node has a pointer to nothingness to
indicate that it is the last node.

Here is the pictorial view of singly linked list:

Here is the pictorial view of inserting an element in the middle of a singly linked list:

Here is the pictorial view of deleting an element in the middle of a singly linked list:

ACTS DEGREE COLLEGE 1


DATA STRUCTURES USING JAVA SEMESTER-IV
Algorithm:

Add at the Start : Add a node the beginning of the linked list. Its O(1).
Add at the End : Add a node at the end of the linked list. its O(n) since to add a node at
the end you need to go till the end of the array.
Delete at the Start : Delete a node from beginning of the linked list. Its O(1).
Delete at the End : Delete a node from the end of the linked list. its O(n) since to delete
a node at the end you need to go till the end of the array.
Get Size: returns the size of the linked list.
Get Element at Index : Return the element at specific index, if index is greater than the
size then return –1. its O(n) in worst case.
Add Element at Specific Index : Add element at specific index. If index is greater than
size then print “INVALID POSITION”. Worst case its O(n)
Display(): Prints the entire linked list. O(n).

Program:
public class LinkListImplementation {
public static void main(String[] args) throws java.lang.Exception {
LinkedListT a = new LinkedListT();
a.addAtBegin(5);
a.addAtBegin(15);
a.addAtEnd(20);
a.addAtEnd(21);
a.deleteAtBegin();
a.deleteAtEnd();
a.addAtIndex(10, 2);
a.addAtEnd(15);
a.display();
System.out.println("\n Size of the list is: " + a.size);
System.out.println(" Element at 2nd position : " + a.elementAt(2));

ACTS DEGREE COLLEGE 2


DATA STRUCTURES USING JAVA SEMESTER-IV
System.out.println(" Searching element 20, location : " + a.search(15));
}
}
class Node {
public int data;
public Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
class LinkedListT {
public Node head;
public int size;
public LinkedListT() {
head = null;
}
public void addAtBegin(int data) {
Node n = new Node(data);
n.next = head;
head = n;
size++;
}
public int deleteAtBegin() {
int tmp = head.data;
head = head.next;
size--;
return tmp;
}
ACTS DEGREE COLLEGE 3
DATA STRUCTURES USING JAVA SEMESTER-IV
public void deleteAtEnd() {
Node currNode = head;
if (head.next == null) {
head = null;
} else {
while (currNode.next.next != null) {
currNode = currNode.next;
}
int temp = currNode.next.data;
currNode.next = null;
size--;
}
}
public void addAtEnd(int data) {
if (head == null) {
addAtBegin(data);
} else {
Node n = new Node(data);
Node currNode = head;
while (currNode.next != null) {
currNode = currNode.next;
}
currNode.next = n;
size++;
}
}
public int elementAt(int index){
if(index>size){
return -1;
ACTS DEGREE COLLEGE 4
DATA STRUCTURES USING JAVA SEMESTER-IV
}
Node n = head;
while(index-1!=0){
n=n.next;
index--;
}
return n.data;
}
public int getSize(){
return size;
}
public int search(int data){
Node n = head;
int count = 1;
while(n!=null){
if(n.data==data){
return count;
}else{
n = n.next;
count++;
}
}
return -1;
}
public void addAtIndex(int data, int position){
if(position == 1){
addAtBegin(data);
}
int len = size;
ACTS DEGREE COLLEGE 5
DATA STRUCTURES USING JAVA SEMESTER-IV
if (position>len+1 || position <1){
System.out.println("\nINVALID POSITION");
}
if(position==len+1){
addAtEnd(data);
}
if(position<=len && position >1){
Node n = new Node(data);
Node currNode = head; //so index is already 1
while((position-2)>0){
System.out.println(currNode.data);
currNode=currNode.next;
position--;
}
n.next = currNode.next;
currNode.next = n;
size++;
}
}
public void display() {
System.out.println("");
Node currNode = head;
while (currNode != null) {
System.out.print("->" + currNode.data);
currNode = currNode.next;
}
}
}

ACTS DEGREE COLLEGE 6


DATA STRUCTURES USING JAVA SEMESTER-IV

Output:

ACTS DEGREE COLLEGE 7


DATA STRUCTURES USING JAVA SEMESTER-IV
(b) Double Linked List:

A doubly-linked list is a linked data structure that consists of a set of sequentially


linked records called nodes. Each node contains two fields, called links, that are
references to the previous and to the next node in the sequence of nodes. The
beginning and ending nodes previous and next links, respectively, point to some kind of
terminator, typically a sentinel node or null, to facilitate traversal of the list. If there is
only one sentinel node, then the list is circularly linked via the sentinel node. It can be
conceptualized as two singly linked lists formed from the same data items, but in
opposite sequential orders.

Here is the pictorial view of doubly linked list:

The two node links allow traversal of the list in either direction. While adding or
removing a node in a doubly-linked list requires changing more links than the same
operations on a singly linked list, the operations are simpler and potentially more
efficient, because there is no need to keep track of the previous node during traversal or
no need to traverse the list to find the previous node, so that its link can be modified.

Here is the pictorial view of inserting an element in the middle of a doubly linked list:

Here is the pictorial view of deleting an element in the middle of a doubly linked list:

ACTS DEGREE COLLEGE 8


DATA STRUCTURES USING JAVA SEMESTER-IV

 
Algorithm:

NOTE: we are two references here, head and tail. Head points the start of the linked


list and tail points to the last node of the linked list.
Add at the Start : Add a node the beginning of the linked list. Its O(1). If size is 0 then
make the new node as head and tail else put the at the start, change the head and do
not change the tail.
Add at the End : Add a node at the end of the linked list. its O(1) since we have tail
reference. If size is 0 then make the new node as head and tail else put node at the end
of the list using tail reference and make the new node as tail.
Delete at the Start : Delete a node from beginning of the linked list and make the
head points to the 2nd node in the list. Its O(1).
Get Size: returns the size of the linked list.
Get Element at Index : Return the element at specific index, if index is greater than
the size then return –1. its O(n) in worst case.
Print: Prints the entire linked list. O(n).

ACTS DEGREE COLLEGE 9


DATA STRUCTURES USING JAVA SEMESTER-IV
Program:

public class DoublyLinkedList(b) {


int size =0;
Node head = null;
Node tail = null;
public Node addAtStart(int data){
System.out.println("Adding Node " + data + " at the start");
Node n = new Node(data);
if(size==0){
head = n;
tail = n;
}else{
n.next = head;
head.previous = n;
head = n;
}
size++;
return n;
}
public Node addAtEnd(int data){
System.out.println("Adding Node " + data + " at the End");
Node n = new Node(data);
if(size==0){
head = n;
tail = n;
}else{
tail.next = n;
n.previous = tail;
tail =n;
}
size++;
return n;
}
public Node addAfter(int data, Node prevNode){
if(prevNode==null){
System.out.println("Node after which new node to be added cannot be null");
return null;
}else if(prevNode==tail){//check if it a last node
return addAtEnd(data);
}else{
ACTS DEGREE COLLEGE 10
DATA STRUCTURES USING JAVA SEMESTER-IV
System.out.println("Adding node after "+ prevNode.data);
//create a new node
Node n = new Node(data);
//store the next node of prevNode
Node nextNode = prevNode.next;
//make new node next points to prevNode
n.next = nextNode;

//make prevNode next points to new Node


prevNode.next = n;
//make nextNode previous points to new node
nextNode.previous = n;
//make new Node previous points to prevNode
n.previous = prevNode;
size++;
return n;
}
}
public void deleteFromStart(){
if(size==0){
System.out.println("\nList is Empty");
}else{
System.out.println("\ndeleting node " + head.data + " from start");
head = head.next;
size--;
}
}
public void deleteFromEnd(){
if(size==0){
System.out.println("\nList is Empty");
}else if(size==1){
deleteFromStart();
}else{
//store the 2nd last node
int x = tail.data;
Node prevTail = tail.previous;
//detach the last node
tail = prevTail;
tail.next=null;
System.out.println("\ndeleting node " + x + " from end");

ACTS DEGREE COLLEGE 11


DATA STRUCTURES USING JAVA SEMESTER-IV
size--;
}
}
public int elementAt(int index){
if(index>size){
return -1;
}
Node n = head;
while(index-1!=0){
n=n.next;
index--;
}
return n.data;
}
//get Size
public int getSize(){
return size;
}
public void print(){
Node temp = head;
System.out.print("Doubly Linked List: ");
while(temp!=null){
System.out.print(" " + temp.data);
temp = temp.next;
}
System.out.println();
}
public static void main(String[] args) {
DoublyLinkedList d = new DoublyLinkedList();
Node x = d.addAtStart(2);
d.addAtStart(1);
d.print();
d.addAtEnd(3);
d.print();
d.addAfter(4,x);
d.print();
d.deleteFromStart();
d.print();
System.out.println("Element at index 2: "+d.elementAt(2));
d.addAtStart(1);

ACTS DEGREE COLLEGE 12


DATA STRUCTURES USING JAVA SEMESTER-IV
d.print();
d.deleteFromEnd();
d.print();
System.out.println("Size of the Linked List: " + d.getSize());
}
}
class Node{
int data;
Node next;
Node previous;
public Node(int data){
this.data = data;
next = null;
previous = null;
}
}

Output:

(c) Circular Linked List

ACTS DEGREE COLLEGE 13


DATA STRUCTURES USING JAVA SEMESTER-IV

Alogrithm:
Add at the Start : Add a node the beginning of the linked list. Its O(1).
Add at the End : Add a node at the end of the linked list. its O(n) since to add a node at
the end you need to go till the end of the array.
Delete at the Start : Delete a node from beginning of the linked list. Its O(1).
Delete at the End : Delete a node from the end of the linked list. its O(n) since to delete
a node at the end you need to go till the end of the array.
Get Size: returns the size of the linked list.
Get Element at Index : Return the element at specific index, if index is greater than the
size then return –1. its O(n) in worst case.
Add Element at Specific Index : Add element at specific index. If index is greater than
size then print “INVALID POSITION”. Worst case its O(n)
Display(): Prints the entire linked list. O(n).
Program:
public class CircularLinkedList {

public int size =0;


public Node head=null;
public Node tail=null;

//add a new node at the start of the linked list


public void addNodeAtStart(int data){
System.out.println("Adding node " + data + " at start");
Node n = new Node(data);
if(size==0){
head = n;
tail = n;
n.next = head;
}else{
Node temp = head;
n.next = temp;
head = n;
tail.next = head;
}
size++;
}

public void addNodeAtEnd(int data){

ACTS DEGREE COLLEGE 14


DATA STRUCTURES USING JAVA SEMESTER-IV
if(size==0){
addNodeAtStart(data);
}else{
Node n = new Node(data);
tail.next =n;
tail=n;
tail.next = head;
size++;
}
System.out.println("\nNode " + data + " is added at the end of the list");
}
public void deleteNodeFromStart(){
if(size==0){
System.out.println("\nList is Empty");
}else{
System.out.println("\ndeleting node " + head.data + " from start");
head = head.next;
tail.next=head;
size--;
}
}
public int elementAt(int index){
if(index>size){
return -1;
}
Node n = head;
while(index-1!=0){
n=n.next;
index--;
}
return n.data;
}
//print the linked list
public void print(){
System.out.print("Circular Linked List:");
Node temp = head;
if(size<=0){
System.out.print("List is empty");
}else{
do {
System.out.print(" " + temp.data);
temp = temp.next;
}
while(temp!=head);
}
System.out.println();

ACTS DEGREE COLLEGE 15


DATA STRUCTURES USING JAVA SEMESTER-IV
}
//get Size
public int getSize(){
return size;
}
public static void main(String[] args) {
CircularLinkedList c = new CircularLinkedList();
c.addNodeAtStart(3);
c.addNodeAtStart(2);
c.addNodeAtStart(1);
c.print();
c.deleteNodeFromStart();
c.print();
c.addNodeAtEnd(4);
c.print();
System.out.println("Size of linked list: "+ c.getSize());
System.out.println("Element at 2nd position: "+ c.elementAt(2));
}
}

class Node{
int data;
Node next;
public Node(int data){
this.data = data;
}
}

Output:

Program - 2
ACTS DEGREE COLLEGE 16
DATA STRUCTURES USING JAVA SEMESTER-IV

2. Write a program to implement the stack operations using array?

 In a Stack, keep track of maximum value in it. It might be the top element in the
stack but once it is poped out, the maximum value should be from the rest of the ele-
ments in the stack.

Approach:
 Create another another Stack(call it as track) which will keep track of maximum in
the given Stack(call it as main).
 When you insert an element in the main stack for the first time (means it is
empty), insert it in the track Stack as well.
 Now onwards when you insert a new element(say it is x) in the main Stack,
peek() the element from the track Stack ( say it is ‘a’). Compare x and a and which
ever is greater, insert it into track Stack.
 When you pop the element from the main stack, pop from the track Stack as well
 So to get to know the maximum  element in the main Stack, peek the element in
the track Stack. ..
 

ACTS DEGREE COLLEGE 17


DATA STRUCTURES USING JAVA SEMESTER-IV
Program:

/**
* @author Nagesh Chauhan
*/
public class StackDemo {
private static final int capacity = 3;
int arr[] = new int[capacity];
int top = -1;

public void push(int pushedElement) {


if (top < capacity - 1) {
top++;
arr[top] = pushedElement;
System.out.println("Element " + pushedElement
+ " is pushed to Stack !");
printElements();
} else {
System.out.println("Stack Overflow !");
}
}

public void pop() {


if (top >= 0) {
top--;
System.out.println("Pop operation done !");
} else {
System.out.println("Stack Underflow !");
}
}

public void printElements() {


if (top >= 0) {
System.out.println("Elements in stack :");
for (int i = 0; i <= top; i++) {
System.out.println(arr[i]);
}
}
}

public static void main(String[] args) {


StackDemo stackDemo = new StackDemo();

stackDemo.pop();
stackDemo.push(23);
stackDemo.push(2);
stackDemo.push(73);
ACTS DEGREE COLLEGE 18
DATA STRUCTURES USING JAVA SEMESTER-IV
stackDemo.push(21);
stackDemo.pop();
stackDemo.pop();
stackDemo.pop();
stackDemo.pop();
}

Output:

Program – 3
ACTS DEGREE COLLEGE 19
DATA STRUCTURES USING JAVA SEMESTER-IV

3. Write a program to implement the queue operations using an array.

Program:

import java.util.*;

class arrayQueue
{
protected int Queue[] ;
protected int front, rear, size, len;
public arrayQueue(int n)
{
size = n;
len = 0;
Queue = new int[size];
front = -1;
rear = -1;
}
public boolean isEmpty()
{
return front == -1;
}
public boolean isFull()
{
return front==0 && rear == size -1 ;
}
public int getSize()
{
return len ;
}
public int peek()
{
if (isEmpty())
throw new NoSuchElementException("Underflow Exception");
return Queue[front];
}
public void insert(int i)
{
if (rear == -1)
{
front = 0;
rear = 0;
Queue[rear] = i;
}
ACTS DEGREE COLLEGE 20
DATA STRUCTURES USING JAVA SEMESTER-IV
else if (rear + 1 >= size)
throw new IndexOutOfBoundsException("Overflow Exception");
else if ( rear + 1 < size)
Queue[++rear] = i;
len++ ;
}
public int remove()
{
if (isEmpty())
throw new NoSuchElementException("Underflow Exception");
else
{
len-- ;
int ele = Queue[front];
if ( front == rear)
{
front = -1;
rear = -1;
}
else
front++;
return ele;
}
}
public void display()
{
System.out.print("\nQueue = ");
if (len == 0)
{
System.out.print("Empty\n");
return ;
}
for (int i = front; i <= rear; i++)
System.out.print(Queue[i]+" ");
System.out.println();
}
}
public class QueueImplement
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);

System.out.println("Array Queue Test\n");


System.out.println("Enter Size of Integer Queue ");
ACTS DEGREE COLLEGE 21
DATA STRUCTURES USING JAVA SEMESTER-IV
int n = scan.nextInt();
arrayQueue q = new arrayQueue(n);
char ch;
do{
System.out.println("\nQueue Operations");
System.out.println("1. insert");
System.out.println("2. remove");
System.out.println("3. peek");
System.out.println("4. check empty");
System.out.println("5. check full");
System.out.println("6. size");
int choice = scan.nextInt();
switch (choice)
{
case 1 :
System.out.println("Enter integer element to insert");
try
{
q.insert( scan.nextInt() );
}
catch(Exception e)
{
System.out.println("Error : " +e.getMessage());
}
break;
case 2 :
try
{
System.out.println("Removed Element = "+q.remove());
}
catch(Exception e)
{
System.out.println("Error : " +e.getMessage());
}
break;
case 3 :
try
{
System.out.println("Peek Element = "+q.peek());
}
catch(Exception e)
{
System.out.println("Error : "+e.getMessage());
}
break;
ACTS DEGREE COLLEGE 22
DATA STRUCTURES USING JAVA SEMESTER-IV
case 4 :
System.out.println("Empty status = "+q.isEmpty());
break;
case 5 :
System.out.println("Full status = "+q.isFull());
break;
case 6 :
System.out.println("Size = "+ q.getSize());
break;
default : System.out.println("Wrong Entry \n ");
break;
}
q.display();
System.out.println("\nDo you want to continue (Type y or n) \n");
ch = scan.next().charAt(0);

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


}
}

Output:

Array Queue Test

Enter Size of Integer Queue


5

Queue Operations
1. insert
2. remove
3. peek
4. check empty
5. check full
6. size
4
Empty status = true

Queue = Empty

Do you want to continue(Type y or n)

Queue Operations
1. insert
ACTS DEGREE COLLEGE 23
DATA STRUCTURES USING JAVA SEMESTER-IV
2. remove
3. peek
4. check empty
5. check full
6. size
1
Enter integer element to insert
24

Queue = 24

Do you want to continue(Type y or n)

Queue Operations
1. insert
2. remove
3. peek
4. check empty
5. check full
6. size
1
Enter integer element to insert
6

Queue = 246

Do you want to continue(Type y or n)

Queue Operations
1. insert
2. remove
3. peek
4. check empty
5. check full
6. size
1
Enter integer element to insert
16

Queue = 24616

Do you want to continue(Type y or n)

ACTS DEGREE COLLEGE 24


DATA STRUCTURES USING JAVA SEMESTER-IV
y

Queue Operations
1. insert
2. remove
3. peek
4. check empty
5. check full
6. size
1
Enter integer element to insert
19

Queue = 2461619

Do you want to continue(Type y or n)

Queue Operations
1. insert
2. remove
3. peek
4. check empty
5. check full
6. size
1
Enter integer element to insert
32

Queue = 246161932

Do you want to continue(Type y or n)

Queue Operations
1. insert
2. remove
3. peek
4. check empty
5. check full
6. size
1
Enter integer element to insert
14
Error : Overflow Exception
ACTS DEGREE COLLEGE 25
DATA STRUCTURES USING JAVA SEMESTER-IV

Queue = 246161932

Do you want to continue(Type y or n)

Queue Operations
1. insert
2. remove
3. peek
4. check empty
5. check full
6. size
5
Full status = true

Queue = 246161932

Do you want to continue(Type y or n)

Queue Operations
1. insert
2. remove
3. peek
4. check empty
5. check full
6. size
3
Peek Element = 24

Queue = 246161932

Do you want to continue(Type y or n)

Queue Operations
1. insert
2. remove
3. peek
4. check empty
5. check full
6. size
2
ACTS DEGREE COLLEGE 26
DATA STRUCTURES USING JAVA SEMESTER-IV
Removed Element = 24

Queue = 6161932

Do you want to continue(Type y or n)

Queue Operations
1. insert
2. remove
3. peek
4. check empty
5. check full
6. size
2
Removed Element = 6

Queue = 161932

Do you want to continue(Type y or n)

Queue Operations
1. insert
2. remove
3. peek
4. check empty
5. check full
6. size
6
Size = 3

Queue = 161932

Do you want to continue(Type y or n)

Queue Operations
1. insert
2. remove
3. peek
4. check empty
5. check full
6. size
ACTS DEGREE COLLEGE 27
DATA STRUCTURES USING JAVA SEMESTER-IV
3
Peek Element = 16

Queue = 161932

Do you want to continue(Type y or n)

Queue Operations
1. insert
2. remove
3. peek
4. check empty
5. check full
6. size
2
Removed Element = 16

Queue = 1932

Do you want to continue(Type y or n)

Queue Operations
1. insert
2. remove
3. peek
4. check empty
5. check full
6. size
2
Removed Element = 19

Queue = 32

Do you want to continue(Type y or n)

y
Queue Operations
1. insert
2. remove
3. peek
4. check empty
5. check full
6. size
ACTS DEGREE COLLEGE 28
DATA STRUCTURES USING JAVA SEMESTER-IV
2
Removed Element = 32

Queue = Empty

Do you want to continue(Type y or n)

Queue Operations
1. insert
2. remove
3. peek
4. check empty
5. check full
6. size
2
Error : Underflow Exception

Queue = Empty

Do you want to continue(Type y or n)

Queue Operations
1. insert
2. remove
3. peek
4. check empty
5. check full
6. size
4
Empty status = true

Queue = Empty

Do you want to continue(Type y or n)


N
Program - 4
4. Write a program to implement the stack operations using a singly linked list.

This is a Java Program to implement a Singly Linked List. A linked list is a data
structure consisting of a group of nodes which together represent a sequence. Under the
simplest form, each node is composed of a data and a reference (in other words, a link)
to the next node in the sequence. This structure allows for efficient insertion or removal
ACTS DEGREE COLLEGE 29
DATA STRUCTURES USING JAVA SEMESTER-IV
of elements from any position in the sequence. In a singly linked list each node has only
one link which points to the next node in the list.
Here is the source code of the Java program to implement Singly Linked List. The Java
program is successfully compiled and run on a Windows system. The program output is
also shown below.
Program:

import java.util.Scanner;

class Node
{
protected int data;
protected Node link;
public Node()
{
link = null;
data = 0;
}
public Node(int d,Node n)
{
data = d;
link = n;
}
public void setLink(Node n)
{
link = n;
}
public void setData(int d)
{
data = d;
}
public Node getLink()
{
return link;
}
public int getData()
{
return data;
}
}

class linkedList
{
protected Node start;
protected Node end ;
ACTS DEGREE COLLEGE 30
DATA STRUCTURES USING JAVA SEMESTER-IV
public int size ;

public linkedList()
{
start = null;
end = null;
size = 0;
}
public boolean isEmpty()
{
return start == null;
}
public int getSize()
{
return size;
}
public void insertAtStart(int val)
{
Node nptr = new Node(val, null);
size++ ;
if(start == null)
{
start = nptr;
end = start;
}
else
{
nptr.setLink(start);
start = nptr;
}
}
public void insertAtEnd(int val)
{
Node nptr = new Node(val,null);
size++ ;
if(start == null)
{
start = nptr;
end = start;
}
else
{
end.setLink(nptr);
end = nptr;
}
}

ACTS DEGREE COLLEGE 31


DATA STRUCTURES USING JAVA SEMESTER-IV
public void insertAtPos(int val , int pos)
{
Node nptr = new Node(val, null);
Node ptr = start;
pos = pos - 1 ;
for (int i = 1; i < size; i++)
{
if (i == pos)
{
Node tmp = ptr.getLink() ;
ptr.setLink(nptr);
nptr.setLink(tmp);
break;
}
ptr = ptr.getLink();
}
size++ ;
}
public void deleteAtPos(int pos)
{
if (pos == 1)
{
start = start.getLink();
size--;
return ;
}
if (pos == size)
{
Node s = start;
Node t = start;
while (s != end)
{
t = s;
s = s.getLink();
}
end = t;
end.setLink(null);
size --;
return;
}
Node ptr = start;
pos = pos - 1 ;
for (int i = 1; i < size - 1; i++)
{
if (i == pos)
{

ACTS DEGREE COLLEGE 32


DATA STRUCTURES USING JAVA SEMESTER-IV
Node tmp = ptr.getLink();
tmp = tmp.getLink();
ptr.setLink(tmp);
break;
}
ptr = ptr.getLink();
}
size-- ;
}
public void display()
{
System.out.print("\nSingly Linked List = ");
if (size == 0)
{
System.out.print("empty\n");
return;
}
if (start.getLink() == null)
{
System.out.println(start.getData() );
return;
}
Node ptr = start;
System.out.print(start.getData()+ "->");
ptr = start.getLink();
while (ptr.getLink() != null)
{
System.out.print(ptr.getData()+ "->");
ptr = ptr.getLink();
}
System.out.print(ptr.getData()+ "\n");
}
}

public class SinglyLinkedList


{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
linkedList list = new linkedList();
System.out.println("Singly Linked List Test\n");
char ch;
do
{
System.out.println("\nSingly Linked List Operations\n");
System.out.println("1. insert at begining");

ACTS DEGREE COLLEGE 33


DATA STRUCTURES USING JAVA SEMESTER-IV
System.out.println("2. insert at end");
System.out.println("3. insert at position");
System.out.println("4. delete at position");
System.out.println("5. check empty");
System.out.println("6. get size");
int choice = scan.nextInt();
switch (choice)
{
case 1 :
System.out.println("Enter integer element to insert");
list.insertAtStart( scan.nextInt() );
break;
case 2 :
System.out.println("Enter integer element to insert");
list.insertAtEnd( scan.nextInt() );
break;
case 3 :
System.out.println("Enter integer element to insert");
int num = scan.nextInt() ;
System.out.println("Enter position");
int pos = scan.nextInt() ;
if (pos <= 1 || pos > list.getSize() )
System.out.println("Invalid position\n");
else
list.insertAtPos(num, pos);
break;
case 4 :
System.out.println("Enter position");
int p = scan.nextInt() ;
if (p < 1 || p > list.getSize() )
System.out.println("Invalid position\n");
else
list.deleteAtPos(p);
break;
case 5 :
System.out.println("Empty status = "+ list.isEmpty());
break;
case 6 :
System.out.println("Size = "+ list.getSize() +" \n");
break;
default :
System.out.println("Wrong Entry \n ");
break;
}
list.display();
System.out.println("\nDo you want to continue (Type y or n) \n");

ACTS DEGREE COLLEGE 34


DATA STRUCTURES USING JAVA SEMESTER-IV
ch = scan.next().charAt(0);
} while (ch == 'Y'|| ch == 'y');
}
}

Output:

Singly Linked List Test

Singly Linked List Operations

1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
5
Empty status = true

Singly Linked List = empty

Do you want to continue(Type y or n)

Singly Linked List Operations

1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
1
Enter integer element to insert
5

Singly Linked List = 5

Do you want to continue(Type y or n)

Singly Linked List Operations

1. insert at begining
ACTS DEGREE COLLEGE 35
DATA STRUCTURES USING JAVA SEMESTER-IV
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
1
Enter integer element to insert
7

Singly Linked List = 7->5

Do you want to continue(Type y or n)

Singly Linked List Operations

1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
2
Enter integer element to insert
4

Singly Linked List = 7->5->4

Do you want to continue(Type y or n)

Singly Linked List Operations

1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
2
Enter integer element to insert
2

Singly Linked List = 7->5->4->2

ACTS DEGREE COLLEGE 36


DATA STRUCTURES USING JAVA SEMESTER-IV
Do you want to continue(Type y or n)

Singly Linked List Operations

1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
1
Enter integer element to insert
9

Singly Linked List = 9->7->5->4->2

Do you want to continue(Type y or n)

Singly Linked List Operations

1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
3
Enter integer element to insert
3
Enter position
3

Singly Linked List = 9->7->3->5->4->2

Do you want to continue(Type y or n)

Singly Linked List Operations

1. insert at begining
2. insert at end
3. insert at position

ACTS DEGREE COLLEGE 37


DATA STRUCTURES USING JAVA SEMESTER-IV
4. delete at position
5. check empty
6. get size
3
Enter integer element to insert
2
Enter position
2

Singly Linked List = 9->2->7->3->5->4->2

Do you want to continue(Type y or n)

Singly Linked List Operations

1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
6
Size = 7

Singly Linked List = 9->2->7->3->5->4->2

Do you want to continue(Type y or n)

Singly Linked List Operations

1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
4
Enter position
4

Singly Linked List = 9->2->7->5->4->2

ACTS DEGREE COLLEGE 38


DATA STRUCTURES USING JAVA SEMESTER-IV
Do you want to continue(Type y or n)

Singly Linked List Operations

1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
4
Enter position
2

Singly Linked List = 9->7->5->4->2

Do you want to continue(Type y or n)

Singly Linked List Operations

1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
4
Enter position
1

Singly Linked List = 7->5->4->2

Do you want to continue(Type y or n)

Singly Linked List Operations

1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty

ACTS DEGREE COLLEGE 39


DATA STRUCTURES USING JAVA SEMESTER-IV
6. get size
4
Enter position
3

Singly Linked List = 7->5->2

Do you want to continue(Type y or n)

Singly Linked List Operations

1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
4
Enter position
1

Singly Linked List = 5->2

Do you want to continue(Type y or n)

Singly Linked List Operations

1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
4
Enter position
2

Singly Linked List = 5

Do you want to continue(Type y or n)

ACTS DEGREE COLLEGE 40


DATA STRUCTURES USING JAVA SEMESTER-IV
Singly Linked List Operations

1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
4
Enter position
1

Singly Linked List = empty

Do you want to continue(Type y or n)

y
Singly Linked List Operations

1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
5
Empty status = true

Singly Linked List = empty


Do you want to continue(Type y or n)
N

Program - 5

5. Write a program to implement the queue operations using a singly linked list.

This is a Java Program to implement a Doubly Linked List. A linked list is a data
structure consisting of a group of nodes which together represent a sequence. Under the
simplest form, each node is composed of a data and a reference (in other words, a link)
to the next node in the sequence. This structure allows for efficient insertion or removal
of elements from any position in the sequence. In a doubly linked list each node has two
links one pointing to the next node in the list and one pointing to the previous node in
the list.
Here is the source code of the Java program to implement Doubly Linked List.
The Java program is successfully compiled and run on a Windows system. The program
output is also shown below.
ACTS DEGREE COLLEGE 41
DATA STRUCTURES USING JAVA SEMESTER-IV
Program:
import java.util.Scanner;
class Node
{
protected int data;
protected Node next, prev;
public Node()
{
next = null;
prev = null;
data = 0;
}
public Node(int d, Node n, Node p)
{
data = d;
next = n;
prev = p;
}
public void setLinkNext(Node n)
{
next = n;
}
public void setLinkPrev(Node p)
{
prev = p;
}
public Node getLinkNext()
{
return next;
}
public Node getLinkPrev()
{
return prev;
}
public void setData(int d)
{
data = d;
}
public int getData()
{
ACTS DEGREE COLLEGE 42
DATA STRUCTURES USING JAVA SEMESTER-IV
return data;
}
}

class linkedList
{
protected Node start;
protected Node end ;
public int size;

public linkedList()
{
start = null;
end = null;
size = 0;
}
public boolean isEmpty()
{
return start == null;
}
public int getSize()
{
return size;
}
public void insertAtStart(int val)
{
Node nptr = new Node(val, null, null);
if(start == null)
{
start = nptr;
end = start;
}
else
{
start.setLinkPrev(nptr);
nptr.setLinkNext(start);
start = nptr;
}
size++;
}

ACTS DEGREE COLLEGE 43


DATA STRUCTURES USING JAVA SEMESTER-IV
public void insertAtEnd(int val)
{
Node nptr = new Node(val, null, null);
if(start == null)
{
start = nptr;
end = start;
}
else
{
nptr.setLinkPrev(end);
end.setLinkNext(nptr);
end = nptr;
}
size++;
}
public void insertAtPos(int val , int pos)
{
Node nptr = new Node(val, null, null);
if (pos == 1)
{
insertAtStart(val);
return;
}
Node ptr = start;
for (int i = 2; i <= size; i++)
{
if (i == pos)
{
Node tmp = ptr.getLinkNext();
ptr.setLinkNext(nptr);
nptr.setLinkPrev(ptr);
nptr.setLinkNext(tmp);
tmp.setLinkPrev(nptr);
}
ptr = ptr.getLinkNext();
}
size++ ;
}
public void deleteAtPos(int pos)

ACTS DEGREE COLLEGE 44


DATA STRUCTURES USING JAVA SEMESTER-IV
{
if (pos == 1)
{
if (size == 1)
{
start = null;
end = null;
size = 0;
return;
}
start = start.getLinkNext();
start.setLinkPrev(null);
size--;
return ;
}
if (pos == size)
{
end = end.getLinkPrev();
end.setLinkNext(null);
size-- ;
}
Node ptr = start.getLinkNext();
for (int i = 2; i <= size; i++)
{
if (i == pos)
{
Node p = ptr.getLinkPrev();
Node n = ptr.getLinkNext();

p.setLinkNext(n);
n.setLinkPrev(p);
size-- ;
return;
}
ptr = ptr.getLinkNext();
}
}
public void display()
{
System.out.print("\nDoubly Linked List = ");

ACTS DEGREE COLLEGE 45


DATA STRUCTURES USING JAVA SEMESTER-IV
if (size == 0)
{
System.out.print("empty\n");
return;
}
if (start.getLinkNext() == null)
{
System.out.println(start.getData() );
return;
}
Node ptr = start;
System.out.print(start.getData()+ " <-> ");
ptr = start.getLinkNext();
while (ptr.getLinkNext() != null)
{
System.out.print(ptr.getData()+ " <-> ");
ptr = ptr.getLinkNext();
}
System.out.print(ptr.getData()+ "\n");
}
}

/* Class DoublyLinkedList */
public class DoublyLinkedList
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
linkedList list = new linkedList();
System.out.println("Doubly Linked List Test\n");
char ch;
do
{
System.out.println("\nDoubly Linked List Operations\n");
System.out.println("1. insert at begining");
System.out.println("2. insert at end");
System.out.println("3. insert at position");
System.out.println("4. delete at position");
System.out.println("5. check empty");
System.out.println("6. get size");

ACTS DEGREE COLLEGE 46


DATA STRUCTURES USING JAVA SEMESTER-IV

int choice = scan.nextInt();


switch (choice)
{
case 1 :
System.out.println("Enter integer element to insert");
list.insertAtStart( scan.nextInt() );
break;
case 2 :
System.out.println("Enter integer element to insert");
list.insertAtEnd( scan.nextInt() );
break;
case 3 :
System.out.println("Enter integer element to insert");
int num = scan.nextInt() ;
System.out.println("Enter position");
int pos = scan.nextInt() ;
if (pos < 1 || pos > list.getSize() )
System.out.println("Invalid position\n");
else
list.insertAtPos(num, pos);
break;
case 4 :
System.out.println("Enter position");
int p = scan.nextInt() ;
if (p < 1 || p > list.getSize() )
System.out.println("Invalid position\n");
else
list.deleteAtPos(p);
break;
case 5 :
System.out.println("Empty status = "+ list.isEmpty());
break;
case 6 :
System.out.println("Size = "+ list.getSize() +" \n");
break;
default :
System.out.println("Wrong Entry \n ");
break;
}

ACTS DEGREE COLLEGE 47


DATA STRUCTURES USING JAVA SEMESTER-IV
/* Display List */
list.display();
System.out.println("\nDo you want to continue (Type y or n) \n");
ch = scan.next().charAt(0);

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


}
}

Output:

Doubly Linked List Test

Doubly Linked List Operations

1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
1
Enter integer element to insert
5

Doubly Linked List = 5

Do you want to continue(Type y or n)

Doubly Linked List Operations

1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
1
Enter integer element to insert
ACTS DEGREE COLLEGE 48
DATA STRUCTURES USING JAVA SEMESTER-IV
2

Doubly Linked List = 2<->5

Do you want to continue(Type y or n)

Doubly Linked List Operations

1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
2
Enter integer element to insert
6

Doubly Linked List = 2<->5<->6

Do you want to continue(Type y or n)

Doubly Linked List Operations

1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
1
Enter integer element to insert
7

Doubly Linked List = 7<->2<->5<->6

Do you want to continue(Type y or n)

ACTS DEGREE COLLEGE 49


DATA STRUCTURES USING JAVA SEMESTER-IV

Doubly Linked List Operations

1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
3
Enter integer element to insert
3
Enter position
3

Doubly Linked List = 7<->2<->3<->5<->6

Do you want to continue(Type y or n)

Doubly Linked List Operations

1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
4
Enter position
2

Doubly Linked List = 7<->3<->5<->6

Do you want to continue(Type y or n)

ACTS DEGREE COLLEGE 50


DATA STRUCTURES USING JAVA SEMESTER-IV
Doubly Linked List Operations

1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
3
Enter integer element to insert
4
Enter position
4

Doubly Linked List = 7<->3<->5<->4<->6

Do you want to continue(Type y or n)

Doubly Linked List Operations

1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
6
Size = 5

Doubly Linked List = 7<->3<->5<->4<->6

Do you want to continue(Type y or n)

Doubly Linked List Operations

1. insert at begining

ACTS DEGREE COLLEGE 51


DATA STRUCTURES USING JAVA SEMESTER-IV
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
4
Enter position
1

Doubly Linked List = 3<->5<->4<->6

Do you want to continue(Type y or n)

Doubly Linked List Operations

1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
4
Enter position
2

Doubly Linked List = 3<->4<->6

Do you want to continue(Type y or n)

Doubly Linked List Operations

1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size

ACTS DEGREE COLLEGE 52


DATA STRUCTURES USING JAVA SEMESTER-IV
4
Enter position
2

Doubly Linked List = 3<->6

Do you want to continue(Type y or n)

Doubly Linked List Operations

1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
4
Enter position
1

Doubly Linked List = 6

Do you want to continue(Type y or n)

Doubly Linked List Operations

1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
4
Enter position
1
Doubly Linked List = empty
Do you want to continue(Type y or n)

ACTS DEGREE COLLEGE 53


DATA STRUCTURES USING JAVA SEMESTER-IV
y
Doubly Linked List Operations
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
5
Empty status = true
Doubly Linked List = empty
Do you want to continue(Type y or n)

Program – 6

6. Write a program for arithmetic expression evaluation.

This is a Java Program to evaluate an expression using stacks. Stack is an area of


memory that holds all local variables and parameters used by any function and
remembers the order in which functions are called so that function returns occur
correctly. ‘push’ operation is used to add an element to stack and ‘pop’ operation is used
to remove an element from stack. ‘peek’ operation is also implemented returning the
value of the top element without removing it. The relation between the push and pop
operations is such that the stack is a Last-In-First-Out (LIFO) data structure.
Here concept of stacks is applied to evaluate an arithmetic expression. This method of
evaluation is commonly employed in calculators and many compilers for parsing the
syntax of expressions, program blocks etc. before translating into low level code.

Program:

/*
ACTS DEGREE COLLEGE 54
DATA STRUCTURES USING JAVA SEMESTER-IV
* Java Program to Evaluate an Expression using Stacks
*/

import java.util.*;

public class EvaluateExpressionUsingStacks


{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
/* Create stacks for operators and operands */
Stack<Integer> op = new Stack<Integer>();
Stack<Double> val = new Stack<Double>();
/* Create temporary stacks for operators and operands */
Stack<Integer> optmp = new Stack<Integer>();
Stack<Double> valtmp = new Stack<Double>();
/* Accept expression */
System.out.println("Evaluation Of Arithmetic Expression Using Stacks Test\n");
System.out.println("Enter expression\n");
String input = scan.next();
input = "0" + input;
input = input.replaceAll("-","+-");
/* Store operands and operators in respective stacks */
String temp = "";
for (int i = 0;i < input.length();i++)
{
char ch = input.charAt(i);
if (ch == '-')
temp = "-" + temp;
else if (ch != '+' && ch != '*' && ch != '/')
temp = temp + ch;
else
{
val.push(Double.parseDouble(temp));
op.push((int)ch);
temp = "";
}
}
val.push(Double.parseDouble(temp));
/* Create char array of operators as per precedence */
/* -ve sign is already taken care of while storing */
char operators[] = {'/','*','+'};
/* Evaluation of expression */
for (int i = 0; i < 3; i++)
{
boolean it = false;

ACTS DEGREE COLLEGE 55


DATA STRUCTURES USING JAVA SEMESTER-IV
while (!op.isEmpty())
{
int optr = op.pop();
double v1 = val.pop();
double v2 = val.pop();
if (optr == operators[i])
{
/* if operator matches evaluate and store in temporary stack */
if (i == 0)
{
valtmp.push(v2 / v1);
it = true;
break;
}
else if (i == 1)
{
valtmp.push(v2 * v1);
it = true;
break;
}
else if (i == 2)
{
valtmp.push(v2 + v1);
it = true;
break;
}
}
else
{
valtmp.push(v1);
val.push(v2);
optmp.push(optr);
}
}
/* Push back all elements from temporary stacks to main stacks */
while (!valtmp.isEmpty())
val.push(valtmp.pop());
while (!optmp.isEmpty())
op.push(optmp.pop());
/* Iterate again for same operator */
if (it)
i--;
}
System.out.println("\nResult = "+val.pop());
}
}

ACTS DEGREE COLLEGE 56


DATA STRUCTURES USING JAVA SEMESTER-IV

OutPut:

Program – 7
7. Write program to implement double ended queue using a doubly linked list

This is a Java Program to implement a Double Ended Queue. Queue is a particular


kind of abstract data type or collection in which the entities in the collection are kept in
order and the principal (or only) operations on the collection are the addition of entities
to the rear terminal position and removal of entities from the front terminal position.
This makes queue a First-In-First-Out (FIFO) data structure. However in a double ended
queue addition and removal of entities can be performed at both ends. A double-ended
queue (dequeue) is an abstract data type that generalizes a queue, for which elements
can be added to or removed from either the front (head) or back (tail).

Program:

/*
* Java Program to Implement Double Ended Queue
*/
ACTS DEGREE COLLEGE 57
DATA STRUCTURES USING JAVA SEMESTER-IV

import java.util.*;

/* Class Node */
class Node
{
protected int data;
protected Node link;

/* Constructor */
public Node()
{
link = null;
data = 0;
}
/* Constructor */
public Node(int d,Node n)
{
data = d;
link = n;
}
/* Function to set link to next Node */
public void setLink(Node n)
{
link = n;
}
/* Function to set data to current Node */
public void setData(int d)
{
data = d;
}
/* Function to get link to next node */
public Node getLink()
{
return link;
}
/* Function to get data from current Node */
public int getData()
{
return data;
}
}

/* Class Dequeue */
class Dequeue
{

ACTS DEGREE COLLEGE 58


DATA STRUCTURES USING JAVA SEMESTER-IV
private Node front, rear;
private int size;

/* Constructor */
public Dequeue()
{
front = null;
rear = null;
size = 0;
}
/* Function to check if queue is empty */
public boolean isEmpty()
{
return front == null;
}
/* Function to get the size of the queue */
public int getSize()
{
return size;
}
/* Clear dequeue */
public void clear()
{
front = null;
rear = null;
size = 0;
}
/* Function to insert an element at begining */
public void insertAtFront(int val)
{
Node nptr = new Node(val, null);
size++ ;
if (front == null)
{
front = nptr;
rear = front;
}
else
{
nptr.setLink(front);
front = nptr;
}
}
/* Function to insert an element at end */
public void insertAtRear(int val)
{

ACTS DEGREE COLLEGE 59


DATA STRUCTURES USING JAVA SEMESTER-IV
Node nptr = new Node(val,null);
size++ ;
if (rear == null)
{
rear = nptr;
front = rear;
}
else
{
rear.setLink(nptr);
rear = nptr;
}
}
/* Function to remove front element from the queue */
public int removeAtFront()
{
if (isEmpty() )
throw new NoSuchElementException("Underflow Exception");
Node ptr = front;
front = ptr.getLink();

if (front == null)
rear = null;
size-- ;

return ptr.getData();
}
/* Function to remove rear element from the queue */
public int removeAtRear()
{
if (isEmpty() )
throw new NoSuchElementException("Underflow Exception");
int ele = rear.getData();
Node s = front;
Node t = front;
while (s != rear)
{
t = s;
s = s.getLink();
}
rear = t;
rear.setLink(null);
size --;

return ele;
}

ACTS DEGREE COLLEGE 60


DATA STRUCTURES USING JAVA SEMESTER-IV
/* Function to check the front element of the queue */
public int peekAtFront()
{
if (isEmpty() )
throw new NoSuchElementException("Underflow Exception");
return front.getData();
}
/* Function to check the front element of the queue */
public int peekAtRear()
{
if (isEmpty() )
throw new NoSuchElementException("Underflow Exception");
return rear.getData();
}
/* Function to display the status of the queue */
public void display()
{
System.out.print("\nDequeue = ");
if (size == 0)
{
System.out.print("Empty\n");
return ;
}
Node ptr = front;
while (ptr != rear.getLink() )
{
System.out.print(ptr.getData()+" ");
ptr = ptr.getLink();
}
System.out.println();
}
}

/* Class DoubleEndedQueueTest */
public class DoubleEndedQueueTest
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
/* Creating object of class Dequeue */
Dequeue dq = new Dequeue();
/* Perform Dequeue Operations */
System.out.println("Dequeue Test\n");
char ch;
do
{

ACTS DEGREE COLLEGE 61


DATA STRUCTURES USING JAVA SEMESTER-IV
System.out.println("\nDequeue Operations");
System.out.println("1. insert at front");
System.out.println("2. insert at rear");
System.out.println("3. delete at front");
System.out.println("4. delete at rear");
System.out.println("5. peek at front");
System.out.println("6. peek at rear");
System.out.println("7. size");
System.out.println("8. check empty");
System.out.println("9. clear");
int choice = scan.nextInt();
switch (choice)
{
case 1 :
System.out.println("Enter integer element to insert");
dq.insertAtFront( scan.nextInt() );
break;
case 2 :
System.out.println("Enter integer element to insert");
dq.insertAtRear( scan.nextInt() );
break;
case 3 :
try
{
System.out.println("Removed Element = "+ dq.removeAtFront());
}
catch (Exception e)
{
System.out.println("Error : " + e.getMessage());
}
break;
case 4 :
try
{
System.out.println("Removed Element = "+ dq.removeAtRear());
}
catch (Exception e)
{
System.out.println("Error : " + e.getMessage());
}
break;
case 5 :
try
{
System.out.println("Peek Element = "+ dq.peekAtFront());
}

ACTS DEGREE COLLEGE 62


DATA STRUCTURES USING JAVA SEMESTER-IV
catch (Exception e)
{
System.out.println("Error : " + e.getMessage());
}
break;
case 6 :
try
{
System.out.println("Peek Element = "+ dq.peekAtRear());
}
catch (Exception e)
{
System.out.println("Error : " + e.getMessage());
}
break;
case 7 :
System.out.println("Size = "+ dq.getSize());
break;
case 8 :
System.out.println("Empty status = "+ dq.isEmpty());
break;
case 9 :
System.out.println("\nDequeue Cleared\n");
dq.clear();
break;
default :
System.out.println("Wrong Entry \n ");
break;
}
/* display dequeue */
dq.display();

System.out.println("\nDo you want to continue (Type y or n) \n");


ch = scan.next().charAt(0);
} while (ch == 'Y'|| ch == 'y');
}
}

Output:

Dequeue Test

Dequeue Operations
1. insert at front
2. insert at rear
3. delete at front

ACTS DEGREE COLLEGE 63


DATA STRUCTURES USING JAVA SEMESTER-IV
4. delete at rear
5. peek at front
6. peek at rear
7. size
8. check empty
9. clear
1
Enter integer element to insert
5

Dequeue = 5

Do you want to continue(Type y or n)


y
Dequeue Operations
1. insert at front
2. insert at rear
3. delete at front
4. delete at rear
5. peek at front
6. peek at rear
7. size
8. check empty
9. clear
1
Enter integer element to insert
8

Dequeue = 85
Do you want to continue(Type y or n)
y
Dequeue Operations
1. insert at front
2. insert at rear
3. delete at front
4. delete at rear
5. peek at front
6. peek at rear
7. size
8. check empty
9. clear
2
Enter integer element to insert
3

Dequeue = 853
Do you want to continue(Type y or n)
ACTS DEGREE COLLEGE 64
DATA STRUCTURES USING JAVA SEMESTER-IV
y
Dequeue Operations
1. insert at front
2. insert at rear
3. delete at front
4. delete at rear
5. peek at front
6. peek at rear
7. size
8. check empty
9. clear
2
Enter integer element to insert
45

Dequeue = 85345
Do you want to continue(Type y or n)
y
Dequeue Operations
1. insert at front
2. insert at rear
3. delete at front
4. delete at rear
5. peek at front
6. peek at rear
7. size
8. check empty
9. clear
1
Enter integer element to insert
28

Dequeue = 2885345
Do you want to continue(Type y or n)
y
Dequeue Operations
1. insert at front
2. insert at rear
3. delete at front
4. delete at rear
5. peek at front
6. peek at rear
7. size
8. check empty
9. clear
5
Peek Element = 28
ACTS DEGREE COLLEGE 65
DATA STRUCTURES USING JAVA SEMESTER-IV

Dequeue = 2885345
Do you want to continue(Type y or n)
y
Dequeue Operations
1. insert at front
2. insert at rear
3. delete at front
4. delete at rear
5. peek at front
6. peek at rear
7. size
8. check empty
9. clear
6
Peek Element = 45

Dequeue = 2885345
Do you want to continue(Type y or n)
y
Dequeue Operations
1. insert at front
2. insert at rear
3. delete at front
4. delete at rear
5. peek at front
6. peek at rear
7. size
8. check empty
9. clear
7
Size = 5

Dequeue = 2885345
Do you want to continue(Type y or n)
y
Dequeue Operations
1. insert at front
2. insert at rear
3. delete at front
4. delete at rear
5. peek at front
6. peek at rear
7. size
8. check empty
9. clear
3
ACTS DEGREE COLLEGE 66
DATA STRUCTURES USING JAVA SEMESTER-IV
Removed Element = 28

Dequeue = 85345
Do you want to continue(Type y or n)
y
Dequeue Operations
1. insert at front
2. insert at rear
3. delete at front
4. delete at rear
5. peek at front
6. peek at rear
7. size
8. check empty
9. clear
4
Removed Element = 45

Dequeue = 853
Do you want to continue(Type y or n)
y
Dequeue Operations
1. insert at front
2. insert at rear
3. delete at front
4. delete at rear
5. peek at front
6. peek at rear
7. size
8. check empty
9. clear
3
Removed Element = 8

Dequeue = 53
Do you want to continue(Type y or n)
y
Dequeue Operations
1. insert at front
2. insert at rear
3. delete at front
4. delete at rear
5. peek at front
6. peek at rear
7. size
8. check empty
9. clear
ACTS DEGREE COLLEGE 67
DATA STRUCTURES USING JAVA SEMESTER-IV
7
Size = 2

Dequeue = 53
Do you want to continue(Type y or n)
y
Dequeue Operations
1. insert at front
2. insert at rear
3. delete at front
4. delete at rear
5. peek at front
6. peek at rear
7. size
8. check empty
9. clear
9

Dequeue Cleared

Dequeue = Empty

Do you want to continue(Type y or n)

Dequeue Operations
1. insert at front
2. insert at rear
3. delete at front
4. delete at rear
5. peek at front
6. peek at rear
7. size
8. check empty
9. clear
8
Empty status = true

Dequeue = Empty

Do you want to continue(Type y or n)

N
ACTS DEGREE COLLEGE 68
DATA STRUCTURES USING JAVA SEMESTER-IV

Program - 8
8. Write a program to search an item in a given list using linear search and binary
search.
(a) Linear Search:

Java program for linear search: Linear search is very simple, To check if an
element is present in the given list we compare search element with every element in
the list. If the number is found then success occurs otherwise the list doesn't contain the
element we are searching.

Program:

/* Java Program Example - Linear Search */

import java.util.Scanner;

public class JavaProgram


{
public static void main(String args[])
{
int arr[] = new int[10];
int i, num, n, c=0, pos=0;
Scanner scan = new Scanner(System.in);

System.out.print("Enter Array Size : ");


n = scan.nextInt();

ACTS DEGREE COLLEGE 69


DATA STRUCTURES USING JAVA SEMESTER-IV
System.out.print("Enter Array Elements : ");
for(i=0; i<n; i++)
{
arr[i] = scan.nextInt();
}

System.out.print("Enter the Number to be Search...");


num = scan.nextInt();

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


{
if(arr[i] == num)
{
c = 1;
pos = i+1;
break;
}
}
if(c == 0)
{
System.out.print("Number Not Found..!!");
}
else
{
System.out.print(num+ " found at position " + pos);
}
}
}

Output:

ACTS DEGREE COLLEGE 70


DATA STRUCTURES USING JAVA SEMESTER-IV

(b) Binary Search

To search any element present inside the array in Java Programming using linear
search technique, you have to use only one for loop to check whether the entered number is
found in the list or not as shown in the following program.

Program:

/* Java Program Example - Binary Search */

import java.util.Scanner;

public class BinarySearch


{

ACTS DEGREE COLLEGE 71


DATA STRUCTURES USING JAVA SEMESTER-IV
public static void main(String args[])
{
int n, i, search, first, last, middle;
int arr[] = new int[50];
Scanner scan = new Scanner(System.in);

System.out.print("Enter Total Number of Elements : ");


n = scan.nextInt();

System.out.print("Enter " +n+ " Elements : ");


for(i=0; i<n; i++)
{
arr[i] = scan.nextInt();
}

System.out.print("Enter a Number to Search..");


search = scan.nextInt();

first = 0;
last = n-1;
middle = (first+last)/2;

while(first <= last)


{
if(arr[middle] < search)
{
first = middle+1;
}
else if(arr[middle] == search)
{
System.out.print(search+ " Found at Location " +middle);
break;
}
else
{
last = middle - 1;
}
middle = (first+last)/2;
}
if(first > last)
{
System.out.print("Not Found..!! " +search+ " is not Present in the List.");
}
}
}

ACTS DEGREE COLLEGE 72


DATA STRUCTURES USING JAVA SEMESTER-IV
Output:

Program - 9

9. Write a program for Quick Sort

This is a Java Program to implement Quick Sort Algorithm. This program is to sort
a list of numbers.
Here is the source code of the Java program to implement Quick Sort Algorithm. The
Java program is successfully compiled and run on a Windows system. The program
output is also shown below.

Program:

import java.util.Scanner;

ACTS DEGREE COLLEGE 73


DATA STRUCTURES USING JAVA SEMESTER-IV
public class QuickSort
{
public static void sort(int[] arr)
{
quickSort(arr, 0, arr.length - 1);
}
public static void quickSort(int arr[], int low, int high)
{
int i = low, j = high;
int temp;
int pivot = arr[(low + high) / 2];

/** partition **/


while (i <= j)
{
while (arr[i] < pivot)
i++;
while (arr[j] > pivot)
j--;
if (i <= j)
{
/** swap **/
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;

i++;
j--;
}
}

if (low < j)
quickSort(arr, low, j);
if (i < high)
quickSort(arr, i, high);
}
public static void main(String[] args)
{
Scanner scan = new Scanner( System.in );
System.out.println("Quick Sort Test\n");
int n, i;
System.out.println("Enter number of integer elements");
n = scan.nextInt();
int arr[] = new int[ n ];
System.out.println("\nEnter "+ n +" integer elements");
for (i = 0; i < n; i++)

ACTS DEGREE COLLEGE 74


DATA STRUCTURES USING JAVA SEMESTER-IV
arr[i] = scan.nextInt();
sort(arr);
System.out.println("\nElements after sorting ");
for (i = 0; i < n; i++)
System.out.print(arr[i]+" ");
System.out.println();
}
}

Out put:

Program - 10

10. Write a program for merge sort

This is a Java Program to implement Merge Sort on an integer array. Merge sort
is an O(n log n) comparison-based sorting algorithm. Most implementations produce a
stable sort, which means that the implementation preserves the input order of equal
elements in the sorted output. Merge sort is a divide and conquer algorithm that was
invented by John von Neumann in 1945.
Conceptually, a merge sort works as follows :

i) Divide the unsorted list into n sublists, each containing 1 element (a list of 1 element
is considered sorted).

ACTS DEGREE COLLEGE 75


DATA STRUCTURES USING JAVA SEMESTER-IV

ii) Repeatedly merge sublists to produce new sublists until there is only 1 sublist
remaining. This will be the sorted list.

Worst case performance : O(n log n)


Best case performance : O(n log n)
Average case performance : O(n log n)

Program:

/*
* Java Program to Implement Merge Sort
*/

import java.util.Scanner;

/* Class MergeSort */
public class MergeSort
{
/* Merge Sort function */
public static void sort(int[] a, int low, int high)
{
int N = high - low;
if (N <= 1)
return;
int mid = low + N/2;
// recursively sort
sort(a, low, mid);
sort(a, mid, high);
// merge two sorted subarrays
int[] temp = new int[N];
int i = low, j = mid;
for (int k = 0; k < N; k++)
{
if (i == mid)
temp[k] = a[j++];
else if (j == high)
temp[k] = a[i++];
else if (a[j]<a[i])
temp[k] = a[j++];
else
temp[k] = a[i++];
}
for (int k = 0; k < N; k++)
a[low + k] = temp[k];

ACTS DEGREE COLLEGE 76


DATA STRUCTURES USING JAVA SEMESTER-IV
}
/* Main method */
public static void main(String[] args)
{
Scanner scan = new Scanner( System.in );
System.out.println("Merge Sort Test\n");
int n, i;
/* Accept number of elements */
System.out.println("Enter number of integer elements");
n = scan.nextInt();
/* Create array of n elements */
int arr[] = new int[ n ];
/* Accept elements */
System.out.println("\nEnter "+ n +" integer elements");
for (i = 0; i < n; i++)
arr[i] = scan.nextInt();
/* Call method sort */
sort(arr, 0, n);
/* Print sorted Array */
System.out.println("\nElements after sorting ");
for (i = 0; i < n; i++)
System.out.print(arr[i]+" ");
System.out.println();
}
}

Output:

ACTS DEGREE COLLEGE 77


DATA STRUCTURES USING JAVA SEMESTER-IV

 
 

Program – 11

11. Write a program on binary search tree operatios (insertion, deletion and traversals)
ACTS DEGREE COLLEGE 78
DATA STRUCTURES USING JAVA SEMESTER-IV

This is a Java Program to implement Binary Search Tree. A binary search tree
(BST), sometimes also called an ordered or sorted binary tree, is a node-based binary
tree data structure which has the following properties:

i) The left subtree of a node contains only nodes with keys less than the node’s
key.
ii) The right subtree of a node contains only nodes with keys greater than the
node’s key.
iii) The left and right subtree must each also be a binary search tree.
iv) There must be no duplicate nodes.
Generally, the information represented by each node is a record rather than a
single data element. However, for sequencing purposes, nodes are compared
according to their keys rather than any part of their associated records. The
major advantage of binary search trees over other data structures is that the
related sorting algorithms and search algorithms such as in-order traversal can be
very efficient. Binary search trees are a fundamental data structure used to
construct more abstract data structures such as sets, multisets, and associative
arrays.

Program:

import java.util.Scanner;

class BSTNode
{
BSTNode left, right;
int data;

public BSTNode()
{
left = null;
right = null;
data = 0;
}
public BSTNode(int n)
{
left = null;
right = null;
data = n;
}
public void setLeft(BSTNode n)
{
left = n;
ACTS DEGREE COLLEGE 79
DATA STRUCTURES USING JAVA SEMESTER-IV
}
public void setRight(BSTNode n)
{
right = n;
}
public BSTNode getLeft()
{
return left;
}
public BSTNode getRight()
{
return right;
}
public void setData(int d)
{
data = d;
}
public int getData()
{
return data;
}
}

class BST
{
private BSTNode root;

public BST()
{
root = null;
}
public boolean isEmpty()
{
return root == null;
}
public void insert(int data)
{
root = insert(root, data);
}
private BSTNode insert(BSTNode node, int data)
{
if (node == null)
node = new BSTNode(data);
else
{
if (data <= node.getData())

ACTS DEGREE COLLEGE 80


DATA STRUCTURES USING JAVA SEMESTER-IV
node.left = insert(node.left, data);
else
node.right = insert(node.right, data);
}
return node;
}
public void delete(int k)
{
if (isEmpty())
System.out.println("Tree Empty");
else if (search(k) == false)
System.out.println("Sorry "+ k +" is not present");
else
{
root = delete(root, k);
System.out.println(k+ " deleted from the tree");
}
}
private BSTNode delete(BSTNode root, int k)
{
BSTNode p, p2, n;
if (root.getData() == k)
{
BSTNode lt, rt;
lt = root.getLeft();
rt = root.getRight();
if (lt == null && rt == null)
return null;
else if (lt == null)
{
p = rt;
return p;
}
else if (rt == null)
{
p = lt;
return p;
}
else
{
p2 = rt;
p = rt;
while (p.getLeft() != null)
p = p.getLeft();
p.setLeft(lt);
return p2;

ACTS DEGREE COLLEGE 81


DATA STRUCTURES USING JAVA SEMESTER-IV
}
}
if (k < root.getData())
{
n = delete(root.getLeft(), k);
root.setLeft(n);
}
else
{
n = delete(root.getRight(), k);
root.setRight(n);
}
return root;
}
public int countNodes()
{
return countNodes(root);
}
private int countNodes(BSTNode r)
{
if (r == null)
return 0;
else
{
int l = 1;
l += countNodes(r.getLeft());
l += countNodes(r.getRight());
return l;
}
}
public boolean search(int val)
{
return search(root, val);
}
private boolean search(BSTNode r, int val)
{
boolean found = false;
while ((r != null) && !found)
{
int rval = r.getData();
if (val < rval)
r = r.getLeft();
else if (val > rval)
r = r.getRight();
else
{

ACTS DEGREE COLLEGE 82


DATA STRUCTURES USING JAVA SEMESTER-IV
found = true;
break;
}
found = search(r, val);
}
return found;
}
public void inorder()
{
inorder(root);
}
private void inorder(BSTNode r)
{
if (r != null)
{
inorder(r.getLeft());
System.out.print(r.getData() +" ");
inorder(r.getRight());
}
}
public void preorder()
{
preorder(root);
}
private void preorder(BSTNode r)
{
if (r != null)
{
System.out.print(r.getData() +" ");
preorder(r.getLeft());
preorder(r.getRight());
}
}
public void postorder()
{
postorder(root);
}
private void postorder(BSTNode r)
{
if (r != null)
{
postorder(r.getLeft());
postorder(r.getRight());
System.out.print(r.getData() +" ");
}
}

ACTS DEGREE COLLEGE 83


DATA STRUCTURES USING JAVA SEMESTER-IV
}

public class BinarySearchTree


{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
BST bst = new BST();
System.out.println("Binary Search Tree Test\n");
char ch;
do
{
System.out.println("\nBinary Search Tree Operations\n");
System.out.println("1. insert ");
System.out.println("2. delete");
System.out.println("3. search");
System.out.println("4. count nodes");
System.out.println("5. check empty");

int choice = scan.nextInt();


switch (choice)
{
case 1 :
System.out.println("Enter integer element to insert");
bst.insert( scan.nextInt() );
break;
case 2 :
System.out.println("Enter integer element to delete");
bst.delete( scan.nextInt() );
break;
case 3 :
System.out.println("Enter integer element to search");
System.out.println("Search result : "+ bst.search( scan.nextInt() ));
break;
case 4 :
System.out.println("Nodes = "+ bst.countNodes());
break;
case 5 :
System.out.println("Empty status = "+ bst.isEmpty());
break;
default :
System.out.println("Wrong Entry \n ");
break;
}
System.out.print("\nPost order : ");
bst.postorder();

ACTS DEGREE COLLEGE 84


DATA STRUCTURES USING JAVA SEMESTER-IV
System.out.print("\nPre order : ");
bst.preorder();
System.out.print("\nIn order : ");
bst.inorder();

System.out.println("\nDo you want to continue (Type y or n) \n");


ch = scan.next().charAt(0);
} while (ch == 'Y'|| ch == 'y');
}
}

Output:

Binary Search Tree Test


Binary Search Tree Operations
1. insert
2. delete
3. search
4. count nodes
5. check empty

Empty status = true


Post order :
Pre order :
In order :
Do you want to continue(Type y or n)

Binary Search Tree Operations

1. insert
2. delete
3. search
4. count nodes
5. check empty
1
Enter integer element to insert
8

Post order : 8
Pre order : 8
In order : 8
Do you want to continue(Type y or n)
y

ACTS DEGREE COLLEGE 85


DATA STRUCTURES USING JAVA SEMESTER-IV
Binary Search Tree Operations

1. insert
2. delete
3. search
4. count nodes
5. check empty
1
Enter integer element to insert
5

Post order : 58
Pre order : 85
In order : 58
Do you want to continue(Type y or n)

Binary Search Tree Operations

1. insert
2. delete
3. search
4. count nodes
5. check empty
1
Enter integer element to insert
3

Post order : 358


Pre order : 853
In order : 358
Do you want to continue(Type y or n)

Binary Search Tree Operations

1. insert
2. delete
3. search
4. count nodes
5. check empty
1
Enter integer element to insert
7

ACTS DEGREE COLLEGE 86


DATA STRUCTURES USING JAVA SEMESTER-IV
Post order : 3758
Pre order : 8537
In order : 3578
Do you want to continue(Type y or n)

Binary Search Tree Operations

1. insert
2. delete
3. search
4. count nodes
5. check empty
1
Enter integer element to insert
10

Post order : 375108


Pre order : 853710
In order : 357810
Do you want to continue(Type y or n)

Binary Search Tree Operations

1. insert
2. delete
3. search
4. count nodes
5. check empty
1
Enter integer element to insert
15

Post order : 37515108


Pre order : 85371015
In order : 35781015
Do you want to continue(Type y or n)

Binary Search Tree Operations

1. insert
2. delete
ACTS DEGREE COLLEGE 87
DATA STRUCTURES USING JAVA SEMESTER-IV
3. search
4. count nodes
5. check empty
1
Enter integer element to insert
2

Post order : 237515108


Pre order : 853271015
In order : 235781015
Do you want to continue(Type y or n)

Binary Search Tree Operations

1. insert
2. delete
3. search
4. count nodes
5. check empty
4
Nodes = 7

Post order : 237515108


Pre order : 853271015
In order : 235781015
Do you want to continue(Type y or n)

Binary Search Tree Operations

1. insert
2. delete
3. search
4. count nodes
5. check empty
3
Enter integer element to search
24
Search result : false

Post order : 237515108


Pre order : 853271015
In order : 235781015
Do you want to continue(Type y or n)
ACTS DEGREE COLLEGE 88
DATA STRUCTURES USING JAVA SEMESTER-IV

Binary Search Tree Operations

1. insert
2. delete
3. search
4. count nodes
5. check empty
3
Enter integer element to search
7
Search result : true

Post order : 237515108


Pre order : 853271015
In order : 235781015
Do you want to continue(Type y or n)

Binary Search Tree Operations

1. insert
2. delete
3. search
4. count nodes
5. check empty
2
Enter integer element to delete
2
2 deleted from the tree

Post order : 37515108


Pre order : 85371015
In order : 35781015
Do you want to continue(Type y or n)

Binary Search Tree Operations

1. insert
2. delete
3. search
4. count nodes
ACTS DEGREE COLLEGE 89
DATA STRUCTURES USING JAVA SEMESTER-IV
5. check empty
2
Enter integer element to delete
8
8 deleted from the tree

Post order : 3751510


Pre order : 1053715
In order : 3571015
Do you want to continue(Type y or n)

Binary Search Tree Operations

1. insert
2. delete
3. search
4. count nodes
5. check empty
2
Enter integer element to delete
10
10 deleted from the tree

Post order : 37515


Pre order : 15537
In order : 35715
Do you want to continue(Type y or n)

Binary Search Tree Operations

1. insert
2. delete
3. search
4. count nodes
5. check empty
2
Enter integer element to delete
5
5 deleted from the tree

Post order : 3715


Pre order : 1573
In order : 3715
ACTS DEGREE COLLEGE 90
DATA STRUCTURES USING JAVA SEMESTER-IV
Do you want to continue(Type y or n)

Binary Search Tree Operations

1. insert
2. delete
3. search
4. count nodes
5. check empty
2
Enter integer element to delete
15
15 deleted from the tree

Post order : 37
Pre order : 73
In order : 37
Do you want to continue(Type y or n)

Binary Search Tree Operations

1. insert
2. delete
3. search
4. count nodes
5. check empty
2
Enter integer element to delete
3
3 deleted from the tree

Post order : 7
Pre order : 7
In order : 7
Do you want to continue(Type y or n)

Binary Search Tree Operations

1. insert
2. delete
3. search
ACTS DEGREE COLLEGE 91
DATA STRUCTURES USING JAVA SEMESTER-IV
4. count nodes
5. check empty
2
Enter integer element to delete
77
Sorry 77 is not present

Post order : 7
Pre order : 7
In order : 7
Do you want to continue(Type y or n)

Binary Search Tree Operations

1. insert
2. delete
3. search
4. count nodes
5. check empty
2
Enter integer element to delete
7
7 deleted from the tree

Post order :
Pre order :
In order :
Do you want to continue(Type y or n)

Binary Search Tree Operations

1. insert
2. delete
3. search
4. count nodes
5. check empty
5
Empty status = true
Post order :
Pre order :
In order :
Do you want to continue(Type y or n)

ACTS DEGREE COLLEGE 92


DATA STRUCTURES USING JAVA SEMESTER-IV
n

Program - 12

12. Write a program for graph traversals

This Java program,performs the DFS traversal on the given graph represented by
a adjacency matrix.the DFS traversal makes use of an stack.
Here is the source code of the Java program to perform the dfs traversal. The Java
program is successfully compiled and run on a Linux system. The program output is also
shown below.
Program:
ACTS DEGREE COLLEGE 93
DATA STRUCTURES USING JAVA SEMESTER-IV

import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.Stack;
public class DFS
{
private Stack<Integer> stack;
public DFS()
{
stack = new Stack<Integer>();
}
public void dfs(int adjacency_matrix[][], int source)
{
int number_of_nodes = adjacency_matrix[source].length - 1;
int visited[] = new int[number_of_nodes + 1];
int element = source;
int i = source;
System.out.print(element + "\t");
visited[source] = 1;
stack.push(source);
while (!stack.isEmpty())
{
element = stack.peek();
i = element;
while (i <= number_of_nodes)
{
if (adjacency_matrix[element][i] == 1 && visited[i] == 0)
{
stack.push(i);
visited[i] = 1;
element = i;
i = 1;
System.out.print(element + "\t");
continue;
}
i++;
}
stack.pop();
}
}
public static void main(String...arg)
{
int number_of_nodes, source;
Scanner scanner = null;
try
{

ACTS DEGREE COLLEGE 94


DATA STRUCTURES USING JAVA SEMESTER-IV
System.out.println("Enter the number of nodes in the graph");
scanner = new Scanner(System.in);
number_of_nodes = scanner.nextInt();
int adjacency_matrix[][] = new int[number_of_nodes + 1]
[number_of_nodes + 1];
System.out.println("Enter the adjacency matrix");
for (int i = 1; i <= number_of_nodes; i++)
for (int j = 1; j <= number_of_nodes; j++)
adjacency_matrix[i][j] = scanner.nextInt();

System.out.println("Enter the source for the graph");


source = scanner.nextInt();
System.out.println("The DFS Traversal for the graph is given by ");
DFS dfs = new DFS();
dfs.dfs(adjacency_matrix, source);
}catch(InputMismatchException inputMismatch)
{
System.out.println("Wrong Input format");
}
scanner.close();
}
}

Output:

ACTS DEGREE COLLEGE 95


DATA STRUCTURES USING JAVA SEMESTER-IV

ACTS DEGREE COLLEGE 96

You might also like