0% found this document useful (0 votes)
52 views48 pages

DS Programs (1-10)

Data Structures

Uploaded by

sas28
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)
52 views48 pages

DS Programs (1-10)

Data Structures

Uploaded by

sas28
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
You are on page 1/ 48

Array implementation of stacks

PROGRAM

import java.util.Scanner;

class Stack

private int top;

private int size;

private int arr[];

Stack(int size)

this.size=size;

this.arr=new int[size];

this.top=-1;

boolean isEmpty()

return(top<0);

boolean push(int val)

if(top==size-1)

System.out.println("Stack Overflow!!");
return false;

else

top++;

arr[top]=val;

System.out.println("Item pushed: "+val);

return true;

boolean pop()

if(top==-1)

System.out.println("Stack Underflow!!");

return false;

else

int poppedValue=arr[top];

top--;

System.out.println("Item Popped: "+poppedValue);

return true;

}
}

void display()

if(top==-1)

System.out.println("No elements in the Stack");

else

System.out.println("The Elements in the Stack");

for(int i=top;i>=0;i--)

System.out.println(arr[i]);

void peek()

if(top==-1)

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

else

{
System.out.println("Top Element is: "+arr[top]);

public class StackOperations

public static void main(String[] args)

Scanner sc=new Scanner(System.in);

System.out.println("Enter the size of the Stack: ");

int size=sc.nextInt();

Stack s=new Stack(size);

int ch=0;

System.out.println("ARRAY IMPLEMENTATION OF STACK \n");

System.out.println("\n----------------------------\n");

while(ch!=5)

System.out.println("\n CHOOSE ONE FOR THE BELOW OPTIONS:


");

System.out.println("\n1. PUSH \n2. POP \n3. PEEK \n4. DISPLAY \n5.


EXIT");

System.out.println("\nEnter your choice: ");

ch=sc.nextInt();

switch(ch)

{
case 1:

System.out.println("Enter the value to push: ");

int value=sc.nextInt();

s.push(value);

break;

case 2:

s.pop();

break;

case 3:

s.peek();

break;

case 4:

s.display();

break;

case 5:

{
System.out.println("EXIT");

break;

default:

System.out.println("Enter a valid choice: ");

sc.close();

}
OUTPUT

RESULT

Thus the given program has been executed successfully.


Array implementation of Queues

PROGRAM

import java.util.Scanner;

class ArrayQueue

private int front, rear, capacity;

private int[] queue;

public ArrayQueue(int size)

capacity=size+1;

queue=new int[capacity];

front=rear=0;

public void enqueue(int item)

if(isFull())

System.out.println("Queue is Full");

return;

queue[rear]=item;

rear=(rear+1)%capacity;

}
public int dequeue()

if(isEmpty())

System.out.println("Queue is empty");

return-1;

int item=queue[front];

front=(front+1)%capacity;

return item;

public boolean isEmpty()

return front==rear;

public boolean isFull()

return(rear+1)%capacity==front;

public void display()

if(isEmpty())

System.out.println("Queue is Empty");
return;

for(int i=front;i!=rear;i=(i+1)%capacity)

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

System.out.println();

public class QueueImplementation

public static void main(String args[])

Scanner scanner=new Scanner(System.in);

System.out.println("Enter the capacity of the queue: ");

int capacity=scanner.nextInt();

ArrayQueue queue=new ArrayQueue(capacity);

while(true)

System.out.println("\nQUEUE OPERATIONS: \n1.ENQUEUE


\n2.DEQUEUE \n3.DISPLAY \n4.EXIT \nCHOOSE A OPTION: ");

int choice=scanner.nextInt();

switch(choice)

case 1:
System.out.println("Enter the element to enqueue: ");

queue.enqueue(scanner.nextInt());

break;

case 2:

int dequeuedElement=queue.dequeue();

if(dequeuedElement!=-1)

System.out.println("Dequeued element: "+dequeuedElement);

break;

case 3:

queue.display();

break;

case 4:

scanner.close();

return;

default:

System.out.println("Enter a valid choice.");

}
OUTPUT

RESULT

Thus the given program has been executed successfully.


Linked list implementation of stacks

PROGRAM
import java.util.Scanner;
public class LinkedListStack {
private Node top;
private class Node {
int data;
Node next;
}
public LinkedListStack() {
top = null;
}
public void push(int data) {
Node newNode = new Node();
newNode.data = data;
newNode.next = top;
top = newNode;
}
public int pop() {
if (top == null) throw new RuntimeException("Stack is Empty");
int data = top.data;
top = top.next;
return data;
}
public boolean isEmpty() {
return top == null;
}
public int peek() {
if (top == null) throw new RuntimeException("Stack is Empty");
return top.data;
}
public void display() {
if (top == null) {
System.out.println("Stack is Empty");
return;
}
System.out.println("Stack Elements:");
Node current = top;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
public static void displayMenu() {
System.out.println("\nEnter your choice:");
System.out.println("1. PUSH");
System.out.println("2. POP");
System.out.println("3. PEEK");
System.out.println("4. DISPLAY STACK ELEMENTS");
System.out.println("5. EXIT");
}
public static void main(String[] args) {
LinkedListStack stack = new LinkedListStack();
Scanner scanner = new Scanner(System.in);
while (true) {
displayMenu();
String choiceStr = scanner.nextLine();
int choice;
try {
choice = Integer.parseInt(choiceStr);
switch (choice) {
case 1:
System.out.println("Enter a value to push:");
int value = Integer.parseInt(scanner.nextLine());
stack.push(value);
break;
case 2:
try {
System.out.println("Popped: " + stack.pop());
} catch (RuntimeException e) {
System.out.println(e.getMessage());
}
break;
case 3:
try {

System.out.println("Top element: " + stack.peek());


} catch (RuntimeException e) {
System.out.println(e.getMessage());
}
break;
case 4:
stack.display();
break;
case 5:
System.out.println("Exiting...");
return;
default:
System.out.println("Invalid choice, please try again.");
}
} catch (NumberFormatException e) {
System.out.println("Enter a valid number.");
}
}
}
}
OUTPUT

RESULT

Thus the given program has been executed successfully.


Linked list implementation of Queues

PROGRAM

import java.util.Scanner;

// Node class for the queue elements

class Node {

int data;

Node next;

Node(int data) {

this.data = data;

this.next = null;

// Queue class using a linked list

class LinkedListQueue {

private Node front, rear;

LinkedListQueue() {

front = rear = null;

// Add an element to the queue

void enqueue(int value) {

Node newNode = new Node(value);

if (rear == null) {
front = rear = newNode;

} else {

rear.next = newNode;

rear = newNode;

System.out.println("Enqueued: " + value);

// Remove an element from the queue

void dequeue() {

if (front == null) {

System.out.println("Queue is empty.");

} else {

System.out.println("Dequeued: " + front.data);

front = front.next;

if (front == null) rear = null;

// View the front element

void peek() {

if (front == null) {

System.out.println("Queue is empty.");

} else {

System.out.println("Front: " + front.data);


}

// Display all elements in the queue

void display() {

if (front == null) {

System.out.println("Queue is empty.");

} else {

System.out.print("Queue: ");

for (Node current = front; current != null; current = current.next) {

System.out.print(current.data + " ");

System.out.println();

public class QueueOperations {

public static void main(String[] args) {

LinkedListQueue queue = new LinkedListQueue();

Scanner sc = new Scanner(System.in);

while (true) {

System.out.println("\n1. Enqueue 2. Dequeue 3. Peek 4. Display


5. Exit");

System.out.print("Choose an option: ");

int choice = sc.nextInt();


switch (choice) {

case 1:

System.out.print("Enter value: ");

queue.enqueue(sc.nextInt());

break;

case 2:

queue.dequeue();

break;

case 3:

queue.peek();

break;

case 4:

queue.display();

break;

case 5:

System.out.println("Exiting...");

sc.close();

return;

default:

System.out.println("Invalid choice. Try again.");

}
OUTPUT

RESULT

Thus the given program has been executed successfully.


Conversion of infix expression to postfix.

PROGRAM

import java.util.Scanner;

import java.util.Stack;

public class InfixToPostfix {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.println("Welcome to the Infix to Postfix Converter!");

System.out.println("Type 'exit' to quit the program at any time.");

while (true) {

System.out.print("Enter an infix expression: ");

String infix = scanner.nextLine().trim();

if (infix.equalsIgnoreCase("exit")) {

System.out.println("Exiting the program. Goodbye!");

break;

if (infix.isEmpty()) {

System.out.println("Error: Expression cannot be empty.");

continue;

String postfix = convertToPostfix(infix);

System.out.println("Postfix Expression: " + postfix);

}
scanner.close();

private static String convertToPostfix(String infix) {

StringBuilder postfix = new StringBuilder();

Stack<Character> stack = new Stack<Character>(); // Older syntax

for (char c : infix.toCharArray()) {

if (Character.isLetterOrDigit(c)) {

postfix.append(c);

} else if (c == '(') {

stack.push(c);

} else if (c == ')') {

processClosingParenthesis(stack, postfix);

} else if (isOperator(c)) {

processOperator(c, stack, postfix);

} else {

return "Error: Invalid character " + c;

// Pop all remaining operators from the stack

while (!stack.isEmpty()) {

char op = stack.pop();

if (op == '(') {

return "Error: Mismatched parentheses";

}
postfix.append(op);

return postfix.toString();

private static void processClosingParenthesis(Stack<Character> stack,


StringBuilder postfix) {

while (!stack.isEmpty() && stack.peek() != '(') {

postfix.append(stack.pop());

if (!stack.isEmpty()) {

stack.pop(); // Remove the '(' from the stack

private static void processOperator(char operator, Stack<Character>


stack, StringBuilder postfix) {

while (!stack.isEmpty() && precedence(operator) <=


precedence(stack.peek())) {

postfix.append(stack.pop());

stack.push(operator);

private static int precedence(char op) {

switch (op) {

case '+':

case '-':
return 1;

case '*':

case '/':

return 2;

case '^':

return 3;

default:

return -1;

private static boolean isOperator(char c) {

return c == '+' || c == '-' || c == '*' || c == '/' || c == '^';

}
OUTPUT

RESULT

Thus the given program has been executed successfully.


Binary Tree Traversals (Inorder, Preorder, Postorder)

PROGRAM

import java.util.Scanner;

import java.util.LinkedList;

import java.util.Queue;

// Node class for the binary tree

class TreeNode {

int data;

TreeNode left, right;

TreeNode(int data) {

this.data = data;

left = right = null;

// Binary Tree class

class BinaryTree {

TreeNode root;

// Method to insert nodes in the binary tree

void insertLevelOrder(int[] elements) {

if (elements.length == 0) return;

root = new TreeNode(elements[0]);

Queue<TreeNode> queue = new LinkedList<TreeNode>();


queue.add(root);

int i = 1;

while (i < elements.length) {

TreeNode current = queue.poll();

if (i < elements.length) {

current.left = new TreeNode(elements[i++]);

queue.add(current.left);

if (i < elements.length) {

current.right = new TreeNode(elements[i++]);

queue.add(current.right);

// Inorder traversal

void inorder(TreeNode node) {

if (node != null) {

inorder(node.left);

System.out.print(node.data + " ");

inorder(node.right);

// Preorder traversal

void preorder(TreeNode node) {


if (node != null) {

System.out.print(node.data + " ");

preorder(node.left);

preorder(node.right);

// Postorder traversal

void postorder(TreeNode node) {

if (node != null) {

postorder(node.left);

postorder(node.right);

System.out.print(node.data + " ");

// Display the binary tree

void display() {

if (root == null) {

System.out.println("The tree is empty.");

return;

// Level order traversal to print the tree

Queue<TreeNode> queue = new LinkedList<TreeNode>();

queue.add(root);

int level = 0;
while (!queue.isEmpty()) {

int levelSize = queue.size();

System.out.print("Level " + level + ": ");

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

TreeNode node = queue.poll();

System.out.print(node.data + " ");

if (node.left != null) queue.add(node.left);

if (node.right != null) queue.add(node.right);

System.out.println();

level++;

public class BinaryTreeTraversals {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

BinaryTree tree = new BinaryTree();

System.out.println("Enter the elements of the tree level by level:");

String input = scanner.nextLine();

String[] inputStrings = input.split(" ");

int[] elements = new int[inputStrings.length];

// Convert input to integers

int count = 0;
for (String s : inputStrings) {

if (s.equalsIgnoreCase("done")) {

break;

elements[count++] = Integer.parseInt(s);

// Build the tree

tree.insertLevelOrder(elements);

while (true) {

System.out.println("\n1. Inorder Traversal 2. Preorder Traversal


3. Postorder Traversal 4. Display Tree 5. Exit");

System.out.print("Choose an option: ");

int choice = scanner.nextInt();

switch (choice) {

case 1:

System.out.print("Inorder Traversal: ");

tree.inorder(tree.root);

System.out.println();

break;

case 2:

System.out.print("Preorder Traversal: ");

tree.preorder(tree.root);

System.out.println();

break;
case 3:

System.out.print("Postorder Traversal: ");

tree.postorder(tree.root);

System.out.println();

break;

case 4:

System.out.println("Tree Structure:");

tree.display();

break;

case 5:

System.out.println("Exiting...");

scanner.close();

return;

default:

System.out.println("Invalid choice. Try again.");

}
OUTPUT

RESULT

Thus the given program has been executed successfully.


Linear Search

PROGRAM

import java.util.Scanner;

public class SimpleLinearSearch {

// Method to find the index of a number

public static int find(int[] numbers, int target) {

for (int i = 0; i < numbers.length; i++) {

if (numbers[i] == target) {

return i; // Found the target

return -1; // Target not found

// Main method

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

// Get the array size and elements

System.out.print("Enter number of elements: ");

int[] numbers = new int[sc.nextInt()];

System.out.println("Enter the elements:");

for (int i = 0; i < numbers.length; i++) {

numbers[i] = sc.nextInt();

}
// Get the target number

System.out.print("Enter number to search: ");

int target = sc.nextInt();

// Search and show result

int index = find(numbers, target);

System.out.println(index == -1 ? "Number not found." : "Number found at


index: " + index);

sc.close();

}
OUTPUT

RESULT

Thus the given program has been executed successfully.


Binary search

PROGRAM

import java.util.Scanner;

public class EasyBinarySearch {

// Method to search for a number

public static int search(int[] arr, int target) {

int start = 0, end = arr.length - 1;

while (start <= end) {

int mid = (start + end) / 2;

if (arr[mid] == target) {

return mid; // Target found

if (arr[mid] < target) {

start = mid + 1; // Search right half

} else {

end = mid - 1; // Search left half

return -1; // Target not found

// Main method to interact with the user

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);


// Get array size

System.out.print("Enter number of elements: ");

int size = sc.nextInt();

int[] arr = new int[size];

// Get array elements

System.out.println("Enter sorted elements:");

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

arr[i] = sc.nextInt();

// Get number to find

System.out.print("Enter number to find: ");

int target = sc.nextInt();

// Perform the search

int result = search(arr, target);

// Display result

if (result == -1) {

System.out.println("Number not found.");

} else {

System.out.println("Number found at index: " + result);

sc.close();

}
OUTPUT

RESULT

Thus the given program has been executed successfully.


Implementation of Depth-First Search & Breadth-First Search of Graphs.

PROGRAM

import java.util.*;
public class SimpleGraphSearch {
// Adjacency list representation of the graph
private static Map<Integer, List<Integer>> graph = new HashMap<Integer,
List<Integer>>();
// Function to add an edge to the graph
private static void addEdge(int u, int v) {
if (!graph.containsKey(u)) {
graph.put(u, new ArrayList<Integer>());
}
if (!graph.containsKey(v)) {
graph.put(v, new ArrayList<Integer>());
}
graph.get(u).add(v);
graph.get(v).add(u);
}
// Depth-First Search (DFS)
private static void dfs(int start, Set<Integer> visited) {
if (visited.contains(start)) return;
visited.add(start);
System.out.print(start + " ");
List<Integer> neighbors = graph.get(start);
if (neighbors != null) {
for (int neighbor : neighbors) {
dfs(neighbor, visited);
}
}
}
// Breadth-First Search (BFS)
private static void bfs(int start) {
Set<Integer> visited = new HashSet<Integer>();
Queue<Integer> queue = new LinkedList<Integer>();
queue.add(start);
visited.add(start);
while (!queue.isEmpty()) {
int node = queue.poll();
System.out.print(node + " ");
List<Integer> neighbors = graph.get(node);
if (neighbors != null) {
for (int neighbor : neighbors) {
if (visited.add(neighbor)) {
queue.add(neighbor);
}}
}}
System.out.println();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("1. Add Edge\n2. DFS\n3. BFS\n4. Exit");
System.out.print("Choose: ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter edge (u v): ");
int u = scanner.nextInt();
int v = scanner.nextInt();
addEdge(u, v);
System.out.println("Edge added.");
break;
case 2:
System.out.print("Enter start node for DFS: ");
Set<Integer> visitedDFS = new HashSet<Integer>();
dfs(scanner.nextInt(), visitedDFS);
System.out.println();
break;
case 3:
System.out.print("Enter start node for BFS: ");
bfs(scanner.nextInt());
break;
case 4:
scanner.close();
return;
default:
System.out.println("Invalid choice.");
}
}
}}
OUTPUT

RESULT

Thus the given program has been executed successfully.


Single source shortest path of a Graph.

PROGRAM

import java.util.*;

public class SimpleDijkstra {

static class Node {

int vertex, weight;

Node(int vertex, int weight) {

this.vertex = vertex;

this.weight = weight;

} }

private static Map<Integer, List<Node>> graph = new


HashMap<Integer, List<Node>>();

private static void addEdge(int u, int v, int weight) {

if (!graph.containsKey(u)) {

graph.put(u, new ArrayList<Node>());

if (!graph.containsKey(v)) {

graph.put(v, new ArrayList<Node>());

graph.get(u).add(new Node(v, weight));

graph.get(v).add(new Node(u, weight));

private static void dijkstra(int source) {


Map<Integer, Integer> distances = new HashMap<Integer,
Integer>();

PriorityQueue<Node> pq = new PriorityQueue<Node>(10, new


Comparator<Node>() {

public int compare(Node a, Node b) {

if (a.weight < b.weight) return -1;

if (a.weight > b.weight) return 1;

return 0;

});

for (int node : graph.keySet()) {

distances.put(node, Integer.MAX_VALUE);

distances.put(source, 0);

pq.add(new Node(source, 0));

while (!pq.isEmpty()) {

Node curr = pq.poll();

int currNode = curr.vertex;

int currDist = curr.weight;

if (currDist > distances.get(currNode)) continue;

List<Node> neighbors = graph.get(currNode);

if (neighbors != null) {

for (Node neighbor : neighbors) {

int newDist = currDist + neighbor.weight;

if (newDist < distances.get(neighbor.vertex)) {


distances.put(neighbor.vertex, newDist);

pq.add(new Node(neighbor.vertex, newDist));

} }

} }

System.out.println("Shortest distances from node " + source + ":");

for (Map.Entry<Integer, Integer> entry : distances.entrySet()) {

System.out.println("To node " + entry.getKey() + ": " +


entry.getValue());

}}

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.println("Enter number of edges:");

int edges = scanner.nextInt();

System.out.println("Enter edges (node1 node2 weight):");

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

int u = scanner.nextInt();

int v = scanner.nextInt();

int weight = scanner.nextInt();

addEdge(u, v, weight);

System.out.println("Enter the source node:");

int source = scanner.nextInt();

dijkstra(source);

}
OUTPUT

RESULT

Thus the given program has been executed successfully.

You might also like