0% found this document useful (0 votes)
11 views40 pages

Ads Lab Record

The document contains Java programs that implement various searching algorithms (linear and binary search) using both recursive and non-recursive methods. It also includes implementations of lists using arrays and linked lists, as well as stack and queue data structures using arrays. Each section provides code examples and basic functionalities for the respective data structures and algorithms.

Uploaded by

Varshi Tha
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)
11 views40 pages

Ads Lab Record

The document contains Java programs that implement various searching algorithms (linear and binary search) using both recursive and non-recursive methods. It also includes implementations of lists using arrays and linked lists, as well as stack and queue data structures using arrays. Each section provides code examples and basic functionalities for the respective data structures and algorithms.

Uploaded by

Varshi Tha
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/ 40

1.

Write Java programs that use both recursive and non-recursive functions for implementing
the following searching methods:
(a) Linear search (b) Binary search
1(a).1 Linear Search using non-recursive function
import java.io.*;
class LinearSearch {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter number of elements (n): ");
int n = Integer.parseInt(br.readLine());
int arr[] = new int[n];
System.out.println("Enter elements:");
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(br.readLine()); }
System.out.print("Enter element to search: ");
int key = Integer.parseInt(br.readLine());
boolean found = false;
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
System.out.println("Element found: " + key + " at position: " + (i + 1));
found = true;
break; // Stop searching after the first occurrence }}
if (!found) {
System.out.println(key + " not found, search failed."); } } }

OUTPUT:
1(a).2 Linear Search using recursive function
import java.io.*;
class RecursiveLinearSearch {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter number of elements (n): ");
int n = Integer.parseInt(br.readLine());
int arr[] = new int[n];
System.out.println("Enter elements:");
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(br.readLine()); }
System.out.print("Enter element to search: ");
int key = Integer.parseInt(br.readLine());
int result = linearSearch(arr, key, n - 1);
if (result != -1)
System.out.println(key + " found at position: " + (result + 1));
else
System.out.println(key + " not found in the list."); }
static int linearSearch(int arr[], int key, int n) {
if (n < 0) return -1; // Base case: if we reach before the first index, key is not found
if (arr[n] == key) return n; // If key is found, return index
return linearSearch(arr, key, n - 1); // Recursive call }}

OUTPUT:
1(b).1 Binary Search using non-recursive function
import java.io.*;
import java.util.Arrays;
class BinarySearch {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter number of elements: ");
int n = Integer.parseInt(br.readLine());
String[] a = new String[n];
System.out.println("Enter elements in sorted order:");
for (int i = 0; i < n; i++) {
a[i] = br.readLine(); }
System.out.print("Enter element to search: ");
String key = br.readLine();
int result = binarySearch(a, key);
if (result != -1)
System.out.println(key + " found at position: " + (result + 1));
else
System.out.println(key + " not found in the list."); }
static int binarySearch(String[] a, String key) {
int low = 0, high = a.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
int c = key.compareTo(a[mid]);
if (c < 0)
high = mid - 1;
else if (c > 0)
low = mid + 1;
else
return mid; // Element found, return index }
return -1; // Element not found }}

OUTPUT:
1(b).2 Binary Search using recursive function
import java.io.*;
import java.util.Arrays;
class RecursiveBinarySearch {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter number of elements: ");
int n = Integer.parseInt(br.readLine());
int arr[] = new int[n];
System.out.println("Enter elements:");
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(br.readLine()); }
// Sorting the array before performing binary search
Arrays.sort(arr);
System.out.println("Sorted array: " + Arrays.toString(arr));
System.out.print("Enter element to search: ");
int key = Integer.parseInt(br.readLine());
int result = binarySearch(arr, key, 0, n - 1);
if (result != -1)
System.out.println(key + " found at position: " + (result + 1));
else
System.out.println(key + " not found in the list."); }
static int binarySearch(int arr[], int key, int low, int high) {
if (low > high)
return -1; // Base case: key not found
int mid = (low + high) / 2;
if (key < arr[mid])
return binarySearch(arr, key, low, mid - 1);
else if (key > arr[mid])
return binarySearch(arr, key, mid + 1, high);
else
return mid; // Key found, return index } }

OUTPUT:

2. Write Java programs to implement the following using arrays and linked lists
a) List using Arrays
import java.io.*;
interface List {
void createList(int n);
void insertFirst(Object ob);
void insertAfter(Object ob, Object pos);
Object deleteFirst();
Object deleteAfter(Object pos);
boolean isEmpty();
int size(); }
class ArrayList implements List {
class Node {
Object data;
int next;
Node(Object ob, int i) { // Constructor
data = ob;
next = i; }}
int MAXSIZE;
Node list[];
int head, count, free;
ArrayList(int s) {
MAXSIZE = s;
list = new Node[MAXSIZE];
head = -1;
count = 0;
free = 0; // Track available nodes
initializeList(); }
public void initializeList() {
for (int p = 0; p < MAXSIZE - 1; p++)
list[p] = new Node(null, p + 1);
list[MAXSIZE - 1] = new Node(null, -1); }
public void createList(int n) {
for (int p = 0; p < n; p++) {
insertFirst(11 + 11 * p); }}
public void insertFirst(Object item) {
if (count == MAXSIZE) {
System.out.println("***List is FULL");
return; }
int p = getNode();
if (p != -1) {
list[p].data = item;
list[p].next = head;
head = p;
count++; }}
public void insertAfter(Object item, Object x) {
if (count == MAXSIZE) {
System.out.println("***List is FULL");
return; }
int p = find(x);
if (p == -1) {
System.out.println("Element " + x + " not found.");
return; }
int q = getNode();
if (q != -1) {
list[q].data = item;
list[q].next = list[p].next;
list[p].next = q;
count++; } }
private int getNode() {
if (free == -1) return -1;
int p = free;
free = list[free].next;
return p; }
private void releaseNode(int p) {
list[p].data = null;
list[p].next = free;
free = p; }
public int find(Object ob) {
int p = head;
while (p != -1) {
if (list[p].data.equals(ob))
return p;
p = list[p].next; }
return -1;}
public Object deleteFirst() {
if (isEmpty()) {
System.out.println("List is empty: no deletion");
return null; }
int p = head;
Object tmp = list[p].data;
head = list[p].next;
releaseNode(p);
count--;
return tmp; }
public Object deleteAfter(Object x) {
int p = find(x);
if (p == -1 || list[p].next == -1) {
System.out.println("No deletion");
return null; }
int q = list[p].next;
Object tmp = list[q].data;
list[p].next = list[q].next;
releaseNode(q);
count--;
return tmp; }
public void display() {
int p = head;
System.out.print("\nList: [ ");
while (p != -1) {
System.out.print(list[p].data + " ");
p = list[p].next; }
System.out.println("]\n"); }
public boolean isEmpty() {
return count == 0; }
public int size() {
return count; } }
class ArrayListDemo {
public static void main(String[] args) {
ArrayList linkedList = new ArrayList(10);
linkedList.createList(4);
linkedList.display();
System.out.print("InsertFirst 55: ");
linkedList.insertFirst(55);
linkedList.display();
System.out.print("Insert 66 after 33: ");
linkedList.insertAfter(66, 33);
linkedList.display();
Object item = linkedList.deleteFirst();
System.out.println("Deleted node: " + item);
linkedList.display();
System.out.print("InsertFirst 77: ");
linkedList.insertFirst(77);
linkedList.display();
item = linkedList.deleteAfter(22);
System.out.println("Deleted node: " + item);
linkedList.display();
System.out.println("Size: " + linkedList.size()); }}

OUTPUT:
b) List Using LinkedList
class LinkedList implements List {
class Node {
Object data; // Data item
Node next; // Pointer to next node
Node(Object d) { // Constructor
data = d;
next = null; }}
private Node head; // Head node
private int count; // Number of nodes
public void insertFirst(Object item) {
Node p = new Node(item);
p.next = head;
head = p;
count++; }
public void insertAfter(Object item, Object key) {
Node p = find(key);
if (p == null) {
System.out.println(key + " key is not found");
} else {
Node q = new Node(item);
q.next = p.next;
p.next = q;
count++; }}
public Node find(Object key) {
Node p = head;
while (p != null) {
if (p.data.equals(key)) // Use .equals() for object comparison
return p;
p = p.next; }
return null; // Not found }
public Object deleteFirst() {
if (isEmpty()) {
System.out.println("List is empty; no deletion");
return null; }
Object tmp = head.data;
head = head.next;
count--;
return tmp; }
public Object deleteAfter(Object key) {
Node p = find(key);
if (p == null) {
System.out.println(key + " key is not found");
return null; }
if (p.next == null) {
System.out.println("No deletion possible");
return null; }
Node tmp = p.next;
p.next = tmp.next;
count--;
return tmp.data; }
public void displayList() {
Node p = head;
System.out.print("\nLinked List: ");
while (p != null) {
System.out.print(p.data + " -> ");
p = p.next; }
System.out.println("null"); }
public boolean isEmpty() {
return (head == null); }
public int size() {
return count; }
public void createList(int n) {
for (int i = 1; i <= n; i++) {
insertFirst(10 * i); // Insert values 10, 20, 30... } } }
class LinkedListDemo {
public static void main(String[] args) {
LinkedList list = new LinkedList(); // Create list object
list.createList(4); // Create 4 nodes
list.displayList();
list.insertFirst(55); // Insert 55 as first node
list.displayList();
list.insertAfter(66, 30); // Insert 66 after 30
list.displayList();
Object item = list.deleteFirst(); // Delete first node
if (item != null) {
System.out.println("deleteFirst(): " + item);
list.displayList(); }
item = list.deleteAfter(20); // Delete a node after node(20)
if (item != null) {
System.out.println("deleteAfter(20): " + item);
list.displayList(); }
System.out.println("size(): " + list.size()); } }

OUTPUT:
3. Write Java programs to implement the following using an array.
(a) Stack ADT (b) Queue ADT
3(a) Stack ADT using array
import java.io.*;
class StackClass {
int top, stack[], size;
StackClass(int n) {
stack = new int[n];
size = n;
top = -1; }
void push(int x) {
if (!isFull()) {
stack[++top] = x;
} else {
System.out.println("Stack Overflow: Cannot push " + x); } }
int pop() {
if (!isEmpty()) {
return stack[top--];
} else {
System.out.println("Stack is empty");
return -1; } }
boolean isEmpty() {
return top == -1; }
boolean isFull() {
return top == size - 1; }
int peek() {
if (!isEmpty()) {
return stack[top];
} else {
System.out.println("Stack is empty");
return -1; } }
int getSize() {
return top + 1; }
void display() {
if (!isEmpty()) {
System.out.print("Stack: ");
for (int i = top; i >= 0; i--) {
System.out.print(stack[i] + " "); }
System.out.println();
} else {
System.out.println("Stack is empty"); }}}
class StackTest {
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the size of stack: ");
int size = Integer.parseInt(br.readLine());
StackClass s = new StackClass(size);
int ch, ele;
do {
System.out.println("\n1. Push");
System.out.println("2. Pop");
System.out.println("3. Peek");
System.out.println("4. Size");
System.out.println("5. Display");
System.out.println("6. Is Empty?");
System.out.println("7. Is Full?");
System.out.println("8. Exit");
System.out.print("Enter your choice: ");
ch = Integer.parseInt(br.readLine());
switch (ch) {
case 1:
if (!s.isFull()) {
System.out.print("Enter the element to insert: ");
ele = Integer.parseInt(br.readLine());
s.push(ele);
} else {
System.out.println("Stack Overflow"); }
break;
case 2:
int del = s.pop();
if (del != -1) {
System.out.println(del + " is deleted"); }
break;
case 3:
int p = s.peek();
if (p != -1) {
System.out.println("Peek element is: " + p); }
break;
case 4:
System.out.println("Size of the stack is: " + s.getSize());
break;
case 5:
s.display();
break;
case 6:
System.out.println("Is Empty? " + s.isEmpty());
break;
case 7:
System.out.println("Is Full? " + s.isFull());
break;
case 8:
System.out.println("Exiting...");
System.exit(0);
default:
System.out.println("Invalid choice! Try again."); }
} while (ch != 8); } }
OUTPUT:
3(b) Queue ADT using array
import java.util.Scanner;
class Queue {
int front, rear, count, max;
int queue[];
Queue(int n) {
max = n;
queue = new int[max];
front = rear = -1;
count = 0; }
boolean isFull() {
return rear == max - 1; }
boolean isEmpty() {
return front == -1; }
void enqueue(int n) {
if (isFull()) {
System.out.println("Queue is full");
} else {
rear++;
queue[rear] = n;
if (front == -1) {
front = 0; }
count++; }}
int dequeue() {
if (isEmpty()) {
System.out.println("Queue is empty, cannot dequeue");
return -1; }
int x = queue[front];
if (front == rear) { // Last element being removed
front = rear = -1;
} else {
front++; }
count--;
return x; }
void display() {
if (isEmpty()) {
System.out.println("Queue is empty");
} else {
System.out.print("Queue: ");
for (int i = front; i <= rear; i++) {
System.out.print(queue[i] + " "); }
System.out.println(); } }
int size() {
return count; }
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
System.out.print("Enter queue limit: ");
int n = s.nextInt();
Queue q = new Queue(n);
int ch;
do {
System.out.println("\n1. Enqueue");
System.out.println("2. Dequeue");
System.out.println("3. Display");
System.out.println("4. Size");
System.out.println("5. Exit");
System.out.print("Enter your choice: ");
ch = s.nextInt();
switch (ch) {
case 1:
System.out.print("Enter element: ");
int element = s.nextInt();
q.enqueue(element);
break;
case 2:
int deleted = q.dequeue();
if (deleted != -1) {
System.out.println("Deleted element is: " + deleted); }
break;
case 3:
q.display();
break;
case 4:
System.out.println("Queue size is: " + q.size());
break;
case 5:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice! Try again."); }
} while (ch != 5);
s.close(); } }
OUTPUT:
4. Write a java program that reads an infix expression, converts the expression to postfix
form and then evaluates the postfix expression (use stack ADT).

import java.util.Scanner;
class Queue {
int front, rear, count, max;
int queue[];
Queue(int n) {
max = n;
queue = new int[max];
front = rear = -1;
count = 0; }
boolean isFull() {
return rear == max - 1; }
boolean isEmpty() {
return front == -1; }
void enqueue(int n) {
if (isFull()) {
System.out.println("Queue is full");
} else {
rear++;
queue[rear] = n;
if (front == -1) {
front = 0; }
count++; } }
int dequeue() {
if (isEmpty()) {
System.out.println("Queue is empty, cannot dequeue");
return -1; }
int x = queue[front];
if (front == rear) { // Last element being removed
front = rear = -1;
} else {
front++; }
count--;
return x; }
void display() {
if (isEmpty()) {
System.out.println("Queue is empty");
} else {
System.out.print("Queue: ");
for (int i = front; i <= rear; i++) {
System.out.print(queue[i] + " "); }
System.out.println(); } }
int size() {
return count; }
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
System.out.print("Enter queue limit: ");
int n = s.nextInt();
Queue q = new Queue(n);
int ch;
do {
System.out.println("\n1. Enqueue");
System.out.println("2. Dequeue");
System.out.println("3. Display");
System.out.println("4. Size");
System.out.println("5. Exit");
System.out.print("Enter your choice: ");
ch = s.nextInt();
switch (ch) {
case 1:
System.out.print("Enter element: ");
int element = s.nextInt();
q.enqueue(element);
break;
case 2:
int deleted = q.dequeue();
if (deleted != -1) {
System.out.println("Deleted element is: " + deleted); }
break;
case 3:
q.display();
break;
case 4:
System.out.println("Queue size is: " + q.size());
break;
case 5:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice! Try again."); }
} while (ch != 5);
s.close(); } }

OUTPUT:
5. Write a Java program to implement circular queue ADT using an array.
class CircularQueue {
private int[] queue;
private int front, rear, size, capacity;
public CircularQueue(int capacity) {
this.capacity = capacity;
queue = new int[capacity];
front = rear = -1;
size = 0; }
public boolean isFull() {
return size == capacity; }
public boolean isEmpty() {
return size == 0; }
public void enqueue(int item) {
if (isFull()) {
System.out.println("Queue is full. Cannot enqueue " + item);
return; }
if (isEmpty()) {
front = rear = 0;
} else {
rear = (rear + 1) % capacity; }
queue[rear] = item;
size++;
System.out.println(item + " enqueued to queue."); }
public int dequeue() {
if (isEmpty()) {
System.out.println("Queue is empty. Cannot dequeue.");
return -1; }
int item = queue[front];
if (front == rear) {
front = rear = -1;
} else {
front = (front + 1) % capacity; }
size--;
System.out.println(item + " dequeued from queue.");
return item; }
public int peek() {
if (isEmpty()) {
System.out.println("Queue is empty. No front element.");
return -1; }
return queue[front]; }
public void display() {
if (isEmpty()) {
System.out.println("Queue is empty.");
return; }
System.out.print("Queue elements: ");
for (int i = 0; i < size; i++) {
System.out.print(queue[(front + i) % capacity] + " "); }
System.out.println(); }
public static void main(String[] args) {
CircularQueue queue = new CircularQueue(5);
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
queue.enqueue(40);
queue.enqueue(50);
queue.display();
queue.dequeue();
queue.dequeue();
queue.display();
queue.enqueue(60);
queue.enqueue(70);
queue.display(); } }

OUTPUT:

10 enqueued to queue.
20 enqueued to queue.
30 enqueued to queue.
40 enqueued to queue.
50 enqueued to queue.
Queue elements: 10 20 30 40 50
10 dequeued from queue.
20 dequeued from queue.
Queue elements: 30 40 50
60 enqueued to queue.
70 enqueued to queue.
Queue elements: 30 40 50 60 70
6. Write a Java program that uses both a stack and a queue to test whether the given string is
a palindrome or not.
6(a) palindrome using stack

import java.util.Stack;
import java.io.*;
class PalindromeST {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter String:");
String str = br.readLine();
str = str.replaceAll("\\s", "").toLowerCase();
if (isPalindrome(str))
System.out.println(str + " is a Palindrome");
else
System.out.println(str + " is not a Palindrome"); }
static boolean isPalindrome(String str) {
Stack<Character> stk = new Stack<>();
for (int i = 0; i < str.length(); i++)
stk.push(str.charAt(i));
for (int i = 0; i < str.length() / 2; i++) {
if (str.charAt(i) != stk.pop())
return false; }
return true; } }

OUTPUT:
6(b) palindrome using queue

import java.util.LinkedList;
import java.io.*;
class PalindromeQ {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter String:");
String str = br.readLine();
str = str.replaceAll("\\s", "").toLowerCase();
if (isPalindrome(str))
System.out.println(str + " is a Palindrome");
else
System.out.println(str + " is not a Palindrome"); }
static boolean isPalindrome(String str) {
LinkedList<Character> que = new LinkedList<Character>();
int n = str.length();
for (int i = 0; i < n; i++) {
que.addLast(str.charAt(i)); }
for (int i = n - 1; i >= n / 2; i--) {
if (str.charAt(i) != que.removeFirst())
return false; }
return true; } }

OUTPUT:
7. Write Java programs to implement the following using a singly linked list.
(a) Stack ADT (b) Queue ADT
7(a) Stack
import java.io.*;
class Stack1 {
Stack1 top, next, prev;
int data;
Stack1() {
data = 0;
next = prev = null; }
Stack1(int d) {
data = d;
next = prev = null; }
void push(int n) {
Stack1 nn = new Stack1(n); // Create a new node
if (top == null) {
top = nn; // If stack is empty, new node is the top
} else {
nn.next = top; // New node points to old top
top.prev = nn; // Old top's prev points to new node
top = nn; // Top becomes the new node } }
int pop() {
if (top == null) {
System.out.println("Stack is empty");
return -1; // Return a sentinel value for empty stack }
int k = top.data; // Store the data of the top element
if (top.next == null) {
top = null;
} else {
top = top.next; // Move top to the next node
top.prev = null; // Disconnect the previous reference }
return k; }
boolean isEmpty() {
return top == null; }
void display() {
if (isEmpty()) {
System.out.println("Stack is empty");
return; }
Stack1 ptr;
for (ptr = top; ptr != null; ptr = ptr.next) {
System.out.print(ptr.data + " "); }
System.out.println(); // To print the newline after the stack elements }
public static void main(String args[]) throws Exception {
int ch;
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
Stack1 a = new Stack1(); // Create a new stack object
do {
System.out.println("Enter 1 for pushing");
System.out.println("Enter 2 for popping");
System.out.println("Enter 3 for isEmpty");
System.out.println("Enter 4 for display");
System.out.println("Enter 0 for exit");
System.out.println("Enter your choice:");
ch = Integer.parseInt(b.readLine()); // Read user choice
switch (ch) {
case 1:
System.out.println("Enter element to insert:");
int e = Integer.parseInt(b.readLine());
a.push(e); // Push element to stack
break;
case 2:
if (!a.isEmpty()) {
int p = a.pop(); // Pop element from stack
System.out.println("Deleted element is " + p);
} else {
System.out.println("Stack is empty"); }
break;
case 3:
System.out.println(a.isEmpty()); // Check if stack is empty
break;
case 4:
a.display(); // Display stack elements
break; }
} while (ch != 0); // Exit the loop when choice is 0 }}

OUTPUT:
7(b). Queue
import java.io.*;
class Qlnk {
Qlnk front, rear, next;
int data;
Qlnk() {
data = 0;
next = null; }
Qlnk(int d) {
data = d;
next = null; }
Qlnk getFront() {
return front; }
Qlnk getRear() {
return rear; }
void insertelm(int item) {
Qlnk nn = new Qlnk(item); // Create new node with item
if (isEmpty()) {
front = rear = nn; // If queue is empty, front and rear point to new node
} else {
rear.next = nn; // Link the current rear to the new node
rear = nn; // Update the rear pointer to new node } }
int delelm() {
if (isEmpty()) {
System.out.println("Deletion failed: Queue is empty");
return -1; // Return -1 if the queue is empty
} else {
int k = front.data; // Store the data of front element
if (front != rear) {
front = front.next; // Move front pointer to the next element
} else {
front = rear = null; // If only one element, set both front and rear to null }
return k; } }
boolean isEmpty() {
return front == null; // If front is null, the queue is empty }
int size() {
Qlnk ptr;
int cnt = 0;
for (ptr = front; ptr != null; ptr = ptr.next) {
cnt++; // Count the number of elements }
return cnt; }
void display() {
Qlnk ptr;
if (!isEmpty()) {
for (ptr = front; ptr != null; ptr = ptr.next) {
System.out.print(ptr.data + " "); // Print the data of each node }
System.out.println(); // To move to the next line after printing elements
} else {
System.out.println("Queue is empty"); } }
public static void main(String arr[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Qlnk m = new Qlnk(); // Create a new queue instance
int ch;
do {
System.out.println("Enter 1 for insert");
System.out.println("Enter 2 for deletion");
System.out.println("Enter 3 for getFront");
System.out.println("Enter 4 for getRear");
System.out.println("Enter 5 for size");
System.out.println("Enter 6 for display");
System.out.println("Enter 0 for exit");
System.out.print("Enter your choice: ");
ch = Integer.parseInt(br.readLine()); // Read user choice
switch (ch) {
case 1:
System.out.print("Enter element to insert: ");
int item = Integer.parseInt(br.readLine());
m.insertelm(item); // Insert element into the queue
break;
case 2:
int k = m.delelm(); // Delete element from the queue
System.out.println("Deleted element is: " + k);
break;
case 3:
System.out.println("Front element is: " + (m.getFront() != null ? m.getFront().data : "Queue is
empty"));
break;
case 4:
System.out.println("Rear element is: " + (m.getRear() != null ? m.getRear().data : "Queue is
empty"));
break;
case 5:
System.out.println("Queue size is: " + m.size()); // Display size of the queue
break;
case 6:
m.display(); // Display all elements in the queue
break; }
} while (ch != 0); // Exit the loop if the user enters 0 }}
OUTPUT:
8. Write Java programs to implement the deque (double ended queue) ADT using
(a) Array (b) Doubly linked list.
(a): An ArrayDeque Class
public class ArrayDeque {
private int maxSize;
private Object[] que;
private int first;
private int last;
private int count; // current number of items in deque
public ArrayDeque(int s) {
maxSize = s;
que = new Object[maxSize];
first = last = -1;
count = 0; }
public void addLast(Object item) {
if (count == maxSize) {
System.out.println("Deque is full");
return; }
last = (last + 1) % maxSize;
que[last] = item;
if (first == -1 && last == 0) first = 0;
count++; }
public Object removeLast() {
if (count == 0) {
System.out.println("Deque is empty");
return null; }
Object item = que[last];
que[last] = null; // Remove the item
last = (last - 1 + maxSize) % maxSize; // Circular decrement
count--;
if (count == 0) {
first = last = -1; // Reset deque to empty state }
return item; }
public void addFirst(Object item) {
if (count == maxSize) {
System.out.println("Deque is full");
return; }
if (first == 0) {
first = maxSize - 1;
} else {
first = (first - 1 + maxSize) % maxSize; // Circular decrement }
que[first] = item;
count++; }
public Object removeFirst() {
if (count == 0) {
System.out.println("Deque is empty");
return null; }
Object item = que[first];
que[first] = null; // Remove the item
first = (first + 1) % maxSize; // Circular increment
count--;
if (count == 0) {
first = last = -1; // Reset deque to empty state }
return item; }
public void display() {
System.out.println("----------------------------");
System.out.print("first: " + first + ", last: " + last);
System.out.println(", count: " + count);
System.out.println("0 1 2 3 4 5");
System.out.print("Deque: ");
for (int i = 0; i < maxSize; i++) {
System.out.print(que[i] + " "); }
System.out.println("\n----------------------------"); }

public boolean isEmpty() {


return (count == 0); // true if queue is empty }
public boolean isFull() {
return (count == maxSize); // true if queue is full }
public static void main(String[] args) {
ArrayDeque q = new ArrayDeque(6); // queue holds a max of 6 items
q.addLast('A'); /* (a) */
q.addLast('B');
q.addLast('C');
q.addLast('D');
System.out.println("removeFirst():" + q.removeFirst());
q.display();
q.addLast('E'); /* (b) */
q.display(); /* (c) */
System.out.println("removeLast():" + q.removeLast());
System.out.println("removeLast():" + q.removeLast());
q.display();
q.addFirst('P');
q.addFirst('Q'); /* (d) */
q.addFirst('R');
q.display();
q.removeFirst();
q.display(); /* (e) */
q.addFirst('X');
q.display(); /* (f) */
q.addLast('Y');
q.display(); /* (g) */
q.addLast('Z');
q.display(); /* (h) */ }}
OUTPUT:
----------------------------
first: 0, last: 3, count: 4
Deque: A B C D null null
----------------------------
removeFirst(): A
----------------------------
first: 1, last: 3, count: 3
Deque: null B C D null null
----------------------------
----------------------------
first: 1, last: 4, count: 4
Deque: null B C D E null
----------------------------
removeLast(): E
removeLast(): D
----------------------------
first: 1, last: 1, count: 2
Deque: null B C null null null
----------------------------
----------------------------
first: 4, last: 1, count: 3
Deque: P Q R C null null
----------------------------
----------------------------
first: 1, last: 1, count: 2
Deque: null Q R C null null
----------------------------
----------------------------
first: 0, last: 1, count: 3
Deque: X Q R C null null
----------------------------
----------------------------
first: 0, last: 2, count: 4
Deque: X Y R C null null
----------------------------
----------------------------
first: 0, last: 3, count: 5
Deque: X Y Z C null null
----------------------------
(b): A LinkedDeque class
public class LinkedDeque {
public class DequeNode {
DequeNode prev;
Object data;
DequeNode next;
DequeNode(Object item) {
data = item; // Set data of the node
prev = next = null; // prev and next automatically refer to null } }
private DequeNode first, last; // First and last nodes of the deque
private int count; // To track the number of elements in the deque
public LinkedDeque() {
first = last = null;
count = 0; }
public void addFirst(Object item) {
DequeNode tmp = new DequeNode(item);
if (isEmpty()) {
first = last = tmp; // If deque is empty, both first and last point to the new node
} else {
tmp.next = first; // Set the new node's next to the current first node
first.prev = tmp; // Set the current first node's prev to the new node
first = tmp; // Move the first pointer to the new node }
count++; }
public void addLast(Object item) {
DequeNode tmp = new DequeNode(item);
if (isEmpty()) {
first = last = tmp; // If deque is empty, both first and last point to the new node
} else {
tmp.prev = last; // Set the new node's prev to the current last node
last.next = tmp; // Set the current last node's next to the new node
last = tmp; // Move the last pointer to the new node }
count++; }
public Object removeFirst() {
if (isEmpty()) {
System.out.println("Deque is empty");
return null;
} else {
Object item = first.data;
first = first.next; // Move the first pointer to the next node
if (first != null) {
first.prev = null; // Set the new first node's prev to null
} else {
last = null; // If deque is now empty, set last to null }
count--;
return item; } }
public Object removeLast() {
if (isEmpty()) {
System.out.println("Deque is empty");
return null;
} else {
Object item = last.data;
last = last.prev; // Move the last pointer to the previous node
if (last != null) {
last.next = null; // Set the new last node's next to null
} else {
first = null; // If deque is now empty, set first to null }
count--;
return item; } }
public Object getFirst() {
if (!isEmpty()) {
return first.data;
} else {
return null; } }
public Object getLast() {
if (!isEmpty()) {
return last.data;
} else {
return null; } }
public boolean isEmpty() {
return (count == 0); }
public int size() {
return count; }
public void display() {
DequeNode p = first;
System.out.print("Deque: [ ");
while (p != null) {
System.out.print(p.data + " ");
p = p.next; }
System.out.println("]"); }}
class LinkedDequeDemo {
public static void main(String[] args) {
LinkedDeque dq = new LinkedDeque();
System.out.println("removeFirst(): " + dq.removeFirst());
dq.addFirst('A');
dq.addFirst('B');
dq.addFirst('C');
dq.display();
dq.addLast('D');
dq.addLast('E');
System.out.println("getFirst(): " + dq.getFirst());
System.out.println("getLast(): " + dq.getLast());
dq.display();
System.out.println("removeFirst(): " + dq.removeFirst());
System.out.println("removeLast(): " + dq.removeLast());
dq.display();
System.out.println("size(): " + dq.size()); }}
OUTPUT:
Deque is empty
removeFirst(): null
Deque: [ C B A ]
getFirst(): C
getLast(): E
Deque: [ C B A D E ]
removeFirst(): C
removeLast(): E
Deque: [ B A D ]
size(): 3
9. Write a Java program to implement a priority queue ADT.
class Node {
String data; // Data item
int prn; // Priority number (lower value = higher priority)
Node next; // Pointer to the next node
Node(String str, int p) { // Constructor
data = str;
prn = p;
next = null; }}
class LinkedPriorityQueue {
Node head; // Reference to the first node
public void insert(String item, int pkey) {
Node newNode = new Node(item, pkey); // Create new node
if (head == null) {
head = newNode;
return; }
if (newNode.prn < head.prn) {
newNode.next = head;
head = newNode;
return; }
Node p = head;
Node prev = null;
while (p != null && newNode.prn >= p.prn) {
prev = p; // Store previous node
p = p.next; // Move forward }
newNode.next = p;
if (prev != null) {
prev.next = newNode; } }
public Node delete() { // Remove the highest-priority element (head)
if (isEmpty()) {
System.out.println("Queue is empty");
return null; }
Node tmp = head;
head = head.next; // Move head to the next node
return tmp; }
public void displayList() {
Node p = head;
System.out.print("\nQueue: ");
while (p != null) {
System.out.print(p.data + "(" + p.prn + ") ");
p = p.next; }
System.out.println(); }
public boolean isEmpty() { // Check if list is empty
return (head == null); }
public Node peek() { // Get the first item (highest priority)
return head; }}
class LinkedPriorityQueueDemo {
public static void main(String[] args) {
LinkedPriorityQueue pq = new LinkedPriorityQueue();
Node item;
pq.insert("Babu", 3);
pq.insert("Nitin", 2);
pq.insert("Laxmi", 2);
pq.insert("Kim", 1);
pq.insert("Jimmy", 3);
pq.displayList();
item = pq.delete();
if (item != null)
System.out.println("delete(): " + item.data + "(" + item.prn + ")");
pq.displayList();
pq.insert("Scot", 2);
pq.insert("Anu", 1);
pq.insert("Lehar", 4);
pq.displayList(); }}

Output:

Queue: Kim(1) Nitin(2) Laxmi(2) Babu(3) Jimmy(3)


delete(): Kim(1)
Queue: Nitin(2) Laxmi(2) Babu(3) Jimmy(3)
Queue: Anu(1) Nitin(2) Laxmi(2) Scot(2) Babu(3) Jimmy(3) Lehar(4)
10. Write a Java program to perform the following operations:
a) Construct a binary search tree of elements.
b) Search for a key element in the above binary search tree.
c) Delete an element from the above binary search tree.
import java.util.*;
class Bstnode {
Bstnode rc, lc;
static Bstnode root;
int data;
Bstnode() {
data = 0;
rc = lc = null; }
Bstnode(int item) {
data = item;
lc = rc = null; }
Bstnode[] search(int key) {
Bstnode par = null, ptr = root;
Bstnode[] b = new Bstnode[2];
while (ptr != null) {
if (ptr.data == key) {
b[0] = par;
b[1] = ptr;
return b;
} else if (ptr.data < key) {
par = ptr;
ptr = ptr.rc;
} else {
par = ptr;
ptr = ptr.lc; // Fix: Corrected syntax error } }
b[0] = par;
b[1] = ptr;
return b;
}
void insert(int item) {
Bstnode[] arr = search(item);
Bstnode nn = new Bstnode(item);
if (root != null) {
Bstnode par = arr[0];
Bstnode ptr = arr[1];
if (ptr != null)
System.out.println("Key already exists");
else {
if (par.data < item)
par.rc = nn;
else
par.lc = nn; }
} else {
root = nn; } }
void inorder(Bstnode ptr) {
if (ptr != null) {
inorder(ptr.lc);
System.out.println(ptr.data);
inorder(ptr.rc); } }
void preorder(Bstnode ptr) {
if (ptr != null) {
System.out.println(ptr.data);
preorder(ptr.lc);
preorder(ptr.rc); } }
void postorder(Bstnode ptr) {
if (ptr != null) {
postorder(ptr.lc);
postorder(ptr.rc);
System.out.println(ptr.data); } }
int deleteLeaf(Bstnode par, Bstnode ptr) {
if (par != null) {
if (par.lc == ptr) {
par.lc = null;
} else {
par.rc = null; }
} else {
root = null; }
return ptr.data; }
int delete1ChildNode(Bstnode par, Bstnode ptr) {
Bstnode child = (ptr.lc != null) ? ptr.lc : ptr.rc;
if (par != null) {
if (par.lc == ptr) {
par.lc = child;
} else {
par.rc = child; }
} else {
root = child;}
return ptr.data; }
int delete2ChildNode(Bstnode par, Bstnode ptr) {
Bstnode succParent = ptr;
Bstnode succ = ptr.rc;
while (succ.lc != null) {
succParent = succ;
succ = succ.lc; }
ptr.data = succ.data;
if (succParent.lc == succ)
succParent.lc = succ.rc;
else
succParent.rc = succ.rc;
return ptr.data; }
int deleteNode(int item) {
Bstnode ptr = root, par = null;
boolean flag = false;
int k = -1;
while (ptr != null) {
if (item < ptr.data) {
par = ptr;
ptr = ptr.lc;
} else if (item > ptr.data) {
par = ptr;
ptr = ptr.rc;
} else {
flag = true;
break; } }
if (!flag) {
System.out.println("Item not found, cannot delete");
return -1; }
if (ptr.lc == null && ptr.rc == null)
k = deleteLeaf(par, ptr);
else if (ptr.lc != null && ptr.rc != null)
k = delete2ChildNode(par, ptr);
else
k = delete1ChildNode(par, ptr);
return k; }
public static void main(String saichandra[]) {
Bstnode b = new Bstnode();
Scanner s = new Scanner(System.in);
int ch;
do {
System.out.println("1. Insert");
System.out.println("2. Delete");
System.out.println("3. Search");
System.out.println("4. Inorder");
System.out.println("5. Preorder");
System.out.println("6. Postorder");
System.out.print("Enter your choice: ");
ch = s.nextInt();
switch (ch) {
case 1:
System.out.print("Enter element: ");
int n = s.nextInt();
b.insert(n);
break;
case 2:
if (root != null) {
System.out.print("Enter element: ");
int n1 = s.nextInt();
int res = b.deleteNode(n1);
if (res != -1)
System.out.println("Deleted element: " + res);
} else
System.out.println("No elements in tree");
break;
case 3:
if (root != null) {
System.out.print("Enter search element: ");
int key = s.nextInt();
Bstnode search1[] = b.search(key);
if (search1[1] != null)
System.out.println("Key is found");
else
System.out.println("Key not found");
} else
System.out.println("No elements in tree");
break;
case 4:
if (root != null)
b.inorder(root);
else
System.out.println("No elements in tree");
break;
case 5:
if (root != null)
b.preorder(root);
else
System.out.println("No elements in tree");
break;
case 6:
if (root != null)
b.postorder(root);
else
System.out.println("No elements in tree");
break; }
} while (ch != 0);
s.close(); }}
OUTPUT:

You might also like