Ads Lab Record
Ads Lab Record
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----------------------------"); }
Output: