0% found this document useful (0 votes)
22 views43 pages

Java Stack and Queue Implementations

The document contains multiple Java programs demonstrating data structures and algorithms, including stack, queue, binary tree traversals, search algorithms, and sorting algorithms. Each program is executed successfully, showcasing functionalities like push/pop for stack, enqueue/dequeue for queue, and various sorting techniques. The document concludes with the successful execution results for each program.

Uploaded by

thirugopi9841
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views43 pages

Java Stack and Queue Implementations

The document contains multiple Java programs demonstrating data structures and algorithms, including stack, queue, binary tree traversals, search algorithms, and sorting algorithms. Each program is executed successfully, showcasing functionalities like push/pop for stack, enqueue/dequeue for queue, and various sorting techniques. The document concludes with the successful execution results for each program.

Uploaded by

thirugopi9841
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PROGRAM CODING:

import [Link];
class Stack {
private int[] stackArray;
private int top;
private int capacity;

public Stack(int size) {


stackArray = new int[size];
capacity = size;
top = -1;
}

public void push(int element) {


if (top == capacity - 1) {
[Link]("Stack Overflow! Cannot add element: " + element);
} else {
stackArray[++top] = element;
[Link]("Pushed: " + element);
}
}

public void pop() {


if (top == -1) {
[Link]("Stack Underflow! Stack is empty.");
} else {
[Link]("Popped: " + stackArray[top--]);
}
}
}

public class StackMain {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the size of the stack: ");
int size = [Link]();
Stack stack = new Stack(size);

while (true) {
[Link]("\n1. Push");
[Link]("2. Pop");
[Link]("4. Exit");
[Link]("Enter your choice: ");
int choice = [Link]();

switch (choice) {
case 1:
[Link]("Enter the element to push: ");
int element = [Link]();
[Link](element);
break;
case 2:
[Link]();
break;
case 3:
[Link]("Exiting...");
[Link]();
return;
default:
[Link]("Invalid choice! Try again.");
}
}
}
}
OUTPUT :

RESULT :

The above program has been executed and verified successfully


PROGRAM CODING:

import [Link];
class Stack {
private Node top;
private class Node {
int data;
Node next;
public Node(int data) {
[Link] = data;
[Link] = null;
}
}
public Stack() {
top = null;
}
public void push(int data) {
Node newNode = new Node(data);
[Link] = top;
top = newNode;
[Link]("Pushed: " + data);
}
public int pop() {
if (isEmpty()) {
[Link]("Stack Underflow! Stack is empty.");
return -1; // Sentinel value
}
int poppedData = [Link];
top = [Link];
[Link]("Popped: " + poppedData);
return poppedData;
}
}

public class StackUsingLinkedList {


public static void main(String[] args) {
Stack stack = new Stack();
Scanner scanner = new Scanner([Link]);

while (true) {
[Link]("\n1. Push");

[Link]("2. Pop");
[Link]("3. Exit");
[Link]("Enter your choice: ");
int choice = [Link]();

switch (choice) {
case 1: // Push
[Link]("Enter the element to push: ");
int element = [Link]();
[Link](element);
break;
case 2: // Pop
[Link]();
break;

case 3: // Exit
[Link]("Exiting...");
[Link]();
return;

default:
[Link]("Invalid choice! Please try again.");
}
}
}
}
OUTPUT :

RESULT :

The above program has been executed and verified successfully


PROGRAM CODING:

class Queue {
private int[] arr;
private int front;
private int rear;
private int capacity;
private int size;

public Queue(int capacity) {


[Link] = capacity; arr =
new int[capacity]; front = 0;
rear = -1;
size = 0;
}
public void enqueue(int element) { if
(isFull()) {
[Link]("Queue is full. Cannot enqueue " + element);
return;
}
arr[++rear] = element; size++;
[Link]("Enqueued: " + element);
}
public int dequeue() { if
(isEmpty()) {
[Link]("Queue is empty. Cannot dequeue.");
return -1;
}
int element = arr[front];
for (int i = 0; i < rear; i++) {
arr[i] = arr[i + 1];
}
rear--;
size--;
[Link]("Dequeued: " + element); return
element;
}
public int peek() { if
(isEmpty()) {
[Link]("Queue is empty. No elements to peek.");
return -1;
}
return arr[front];
}
public boolean isEmpty() { return
size == 0;
}
public boolean isFull() { return
size == capacity;
}
public int size() { return
size;
}
}
public class Main {
public static void main(String[] args) { Queue
queue = new Queue(5);

[Link](10);
[Link](20);
[Link](30);
[Link](40);
[Link](50);

[Link]("Front element is: " + [Link]());

[Link]();
[Link]();

[Link](60);

[Link]("Front element is: " + [Link]());


[Link]("Queue size is: " + [Link]());
}
}
OUTPUT :

RESULT :

The above program has been executed and verified successfully


PROGRAM CODING:

class Node {
int data;
Node next;
public Node(int data) {

[Link] = data;
[Link] = null;
}
}
class Queue {
private Node front;
private Node rear;
private int size;

public Queue() { [Link]


= null; [Link] = null;
[Link] = 0;
}
public void enqueue(int element) {
Node newNode = new Node(element); if
(isEmpty()) {
front = rear = newNode;
} else {
[Link] = newNode;
rear = newNode;
}
size++;
[Link]("Enqueued: " + element);
}
public int dequeue() { if
(isEmpty()) {
[Link]("Queue is empty. Cannot dequeue.");

return -1;
}
int element = [Link]; front =
[Link];
if (front == null) {
rear = null;
}
size--;
[Link]("Dequeued: " + element); return
element;
}
public int peek() { if
(isEmpty()) {
[Link]("Queue is empty. No elements to peek.");
return -1;
}
return [Link];
}
public boolean isEmpty() { return
front == null;
}
public int size() { return
size;
}
}
public class Main {
public static void main(String[] args) {

Queue queue = new Queue(); // Create an empty queue

[Link](10);
[Link](20);
[Link](30);
[Link](40);

[Link]("Front element is: " + [Link]());

[Link]();
[Link]();

[Link]("Front element is: " + [Link]());


[Link]("Queue size is: " + [Link]());

[Link](50);
[Link]("Front element is: " + [Link]());
}
}
OUTPUT :

RESULT :

The above program has been executed and verified successfully


PROGRAM CODING:

import [Link];
class Main {
int prec(char c) {
if (c == '^')
return 3;
else if (c == '/' || c == '*') return 2;
else if (c == '+' || c == '-') return 1;
else
return -1;
}
String infixToPostfix(String s) {
Stack<Character> st = new Stack<>();
StringBuilder result = new StringBuilder();

for (int i = 0; i < [Link](); i++) { char c =


[Link](i);
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))
[Link](c);
else if (c == '(')
[Link]('(');
else if (c == ')') {
while ([Link]() != '(') {
[Link]([Link]());
}
[Link]();
} else {
while (![Link]() && (prec(c) <= prec([Link]()))) {
[Link]([Link]());
}
[Link](c);
}
}
while (![Link]()) {
[Link]([Link]());
}
return [Link]();
}
public static void main(String[] args)
{ Main obj = new Main();
String infixexp = "a+b*(c^d-e)^(f+g*h)-i";
String postfixexp =
[Link](infixexp);
[Link]("Infix: " + infixexp);
[Link]("Postfix: " + postfixexp);
}
}
OUTPUT :

RESULT :

The above program has been executed and verified successfully


PROGRAM CODING:

class Node {
public int value;
public Node left, right;

public Node(int element)

value = element; left =


right = null;
}

class Tree {
Node root;

Tree() { root = null; }

void traversePreorder(Node node)

{
if (node == null)
return;
[Link]([Link] + " ");
traversePreorder([Link]);
traversePreorder([Link]);
}

void traverseInorder(Node node)


{

if (node == null)
return;
traverseInorder([Link]);
[Link]([Link] + " ");
traverseInorder([Link]);
}
void traversePostorder(Node node)

if (node == null)
return;
traversePostorder([Link]);
traversePostorder([Link]);
[Link]([Link] + " ");
}

void traversePreorder() { traversePreorder(root); }


void traverseInorder() { traverseInorder(root); }
void traversePostorder() { traversePostorder(root); }

public static void main(String args[])


{

Tree pt = new Tree(); [Link] =


new Node(36); [Link] = new
Node(26);
[Link] = new Node(46); [Link] =
new Node(21); [Link] = new
Node(31); [Link] = new Node(11);
[Link] = new Node(24);
[Link] = new Node(41);
[Link] = new Node(56);
[Link] = new Node(51);
[Link] = new Node(66);

[Link]();

[Link]("The Preorder traversal of given binary tree is - "); [Link]();


[Link]("\n");

[Link]("The Inorder traversal of given binary tree is - "); [Link]();


[Link]("\n");

[Link]("The Postorder traversal of given binary tree is - "); [Link]();


[Link]();

}
OUTPUT :

RESULT :

The above program has been executed and verified successfully


PROGRAM CODING:

import [Link];
public class SearchAlgorithms {
public static int linearSearch(int[] arr, int key) { for (int i = 0; i < [Link]; i++) {
if (arr[i] == key) { return i;
}
}
return -1;
}
public static int binarySearch(int[] arr, int key, int left, int right) { if (left <= right) {
int mid = left + (right - left) / 2; if (arr[mid] == key) {
return mid; // Key found at index mid
}
if (arr[mid] > key) {
return binarySearch(arr, key, left, mid - 1); } return binarySearch(arr, key, mid + 1, right);
}
return -1;
}
public static void main(String[] args) { int[] array = {10, 25, 30, 40, 50, 60, 70};
int key = 40;
int linearResult = linearSearch(array, key);
[Link]("Linear Search: Element found at index: " + linearResult);
[Link](array); // Ensure array is sorted
int binaryResult = binarySearch(array, key, 0, [Link] - 1);
[Link]("Binary Search: Element found at index: " + binaryResult);
}
}
OUTPUT :

RESULT :

The above program has been executed and verified successfully


PROGRAM CODING:

import [Link];
public class SortingAlgorithms {
public static void mergeSort(int[] arr, int left, int right) { if
(left < right) {
int mid = (left + right) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
private static void merge(int[] arr, int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid; int[]
L = new int[n1]; int[] R =
new int[n2];
[Link](arr, left, L, 0, n1);
[Link](arr, mid + 1, R, 0, n2);
int i = 0, j = 0;
int k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
public static void main(String[] args) { int[]
arr = {12, 11, 13, 5, 6, 7};
mergeSort(arr, 0, [Link] - 1); [Link]("Merge
Sort: " + [Link](arr));
}
}
OUTPUT :

RESULT :

The above program has been executed and verified successfully


PROGRAM CODING:

import [Link];
public class SortingAlgorithms {
public static void quickSort(int[] arr, int low, int high) { if
(low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
private static int partition(int[] arr, int low, int high) { int
pivot = arr[high];
int i = (low - 1);
for (int j = low; j < high; j++) {
if (arr[j] <= pivot) {
i++;
swap(arr, i, j);
}
}
swap(arr, i + 1, high); return i +
1;
}
private static void swap(int[] arr, int i, int j) { int
temp = arr[i];
arr[i] = arr[j]; arr[j] =
temp;
}
public static void main(String[] args) { int[]
arr = {12, 11, 13, 5, 6, 7};
quickSort(arr, 0, [Link] - 1); [Link]("Quick
Sort: " + [Link](arr));
}
}
OUTPUT :

RESULT :

The above program has been executed and verified successfully


PROGRAM CODING:

import [Link];
public class SortingAlgorithms {
public static void insertionSort(int[] arr) {
int n = [Link];

for (int i = 1; i < n; i++) { int key = arr


[Link]("Insertion Sort: " + [Link](arr));
}
}
[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
public static void main(String[] args) { int[]
arr = {12, 11, 13, 5, 6, 7};
insertionSort(arr);
OUTPUT :

RESULT :

The above program has been executed and verified successfully


PROGRAM CODING:

import [Link].*;
public class Graph {
private int V;
private LinkedList<Integer> adj[];
Graph(int v) {
V = v;
adj = new LinkedList[v]; for
(int i = 0; i < v; ++i) adj[i] =
new LinkedList();
}
void addEdge(int v, int w) {
adj[v].add(w);
}
void BFS(int s) {
boolean visited[] = new boolean[V]; LinkedList<Integer>
queue = new LinkedList(); visited[s] = true;
[Link](s);
while ([Link]() != 0) {
s = [Link]();
[Link](s + " ");
Iterator<Integer> i = adj[s].listIterator();
while ([Link]()) {
int n = [Link]();
if (!visited[n]) {
visited[n] = true;
[Link](n);
}
}
}
}
public static void main(String args[]) {
Graph g = new Graph(4); [Link](0,
1);
[Link](0, 2);
[Link](1, 2);
[Link](2, 0);
[Link](2, 3);
[Link](3, 3);
[Link]("Following is Breadth First Traversal " + "(starting from vertex 2)");
[Link](2);
}
}
OUTPUT :

RESULT :

The above program has been executed and verified successfully


PROGRAM CODING:

import [Link].*;
class Graph {
private LinkedList<Integer> adjLists[];
private boolean visited[];
Graph(int vertices) {
adjLists = new LinkedList[vertices]; visited
= new boolean[vertices];
for (int i = 0; i < vertices; i++)
adjLists[i] = new LinkedList<Integer>();
}
void addEdge(int src, int dest) {
adjLists[src].add(dest);
}
void DFS(int vertex) {
visited[vertex] = true;
[Link](vertex + " ");
Iterator<Integer> ite = adjLists[vertex].listIterator(); while
([Link]()) {
int adj = [Link]();
if (!visited[adj])
DFS(adj);
}
}
public static void main(String args[]) {
Graph g = new Graph(4); [Link](0,
1);
[Link](0, 2);
[Link](1, 2);
[Link](2, 3);
[Link]("Following is Depth First Traversal"); [Link](2);
}
}
OUTPUT :

RESULT :

The above program has been executed and verified successfully


PROGRAM CODING:

import [Link].*;
C import
[Link].*; class
ShortestPath {
static final int V = 9;
int minDistance(int dist[], Boolean sptSet[])
{
int min = Integer.MAX_VALUE, min_index = -1;

for (int v = 0; v < V; v++)


if (sptSet[v] == false && dist[v]
<=min) { min = dist[v];
min_index = v;
}
return min_index;
}
void printSolution(int dist[], int n)
{
[Link]("Vertex Distance from Source"); for (int i =
0; i < V; i++)
[Link](i + " " + dist[i]);
}

void dijkstra(int graph[][], int src)


{

int dist[] = new int[V];


Boolean sptSet[] = new Boolean[V]; for (int i = 0;
i < V; i++) {
dist[i] = Integer.MAX_VALUE;
sptSet[i] = false;
}

dist[src] = 0;
for (int count = 0; count < V - 1;
count++) { int u =
minDistance(dist, sptSet);
sptSet[u] = true;
for (int v = 0; v < V; v++)
if (!sptSet[v] && graph[u][v] != 0 &&
dist[u] != Integer.MAX_VALUE && dist[u] + graph[u][v] <
dist[v]) dist[v] = dist[u] + graph[u][v];
}

printSolution(dist, V);
}
public static void main(String[] args)
{

int graph[][] = new int[][] { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },


{ 4, 0, 8, 0, 0, 0, 0, 11, 0 },
{ 0, 8, 0, 7, 0, 4, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 4, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 11, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 } };

ShortestPath t = new ShortestPath(); [Link](graph, 0);


}
}
OUTPUT :

RESULT :

The above program has been executed and verified successfully

You might also like