0% found this document useful (0 votes)
5 views37 pages

Ashish Ada Lab File

The document is an assignment submission for Advance Data Structure & Algorithm by Ashish Kumar Sinha from Galgotias University. It includes a series of experiments with Java programs that implement various data structures and algorithms, such as stacks, queues, binary trees, AVL trees, and graph traversal methods. Each experiment contains an aim, program code, and output examples demonstrating the functionality of the implemented algorithms.
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)
5 views37 pages

Ashish Ada Lab File

The document is an assignment submission for Advance Data Structure & Algorithm by Ashish Kumar Sinha from Galgotias University. It includes a series of experiments with Java programs that implement various data structures and algorithms, such as stacks, queues, binary trees, AVL trees, and graph traversal methods. Each experiment contains an aim, program code, and output examples demonstrating the functionality of the implemented algorithms.
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/ 37

Assignment of

Advance Data Structure & Algorithm


Submitted in partial fulfillment of the

requirement for the award of the degree of

School of Computer Science Engineering

Submitted By

Ashish Kumar Sinha


21SCSE1011493

SCHOOL OF COMPUTING SCIENCE AND ENGINEERING DEPARTMENT OF


COMPUTER SCIENCE AND ENGINEERING
GALGOTIAS UNIVERSITY, GREATER NOIDA
INDIA
Index
S.No Experiment Name Date Signature

1 Write a java program to implement stack operation using linked list


implementation of stack.

2 Write a java program to implement tower of hanoi.

3 write a java program to convert infix expression to postfix and


evaluate it.

4 Write a program to implement queue operation using linked list


implementation.

5 Write a java program to implement Binary search Tree

6 Write a java program to construct binary tree using given tree


traversal

7 Write a java program for B+ tree

8 Write a java program to implement AVL tree.

9 Write a java program to implement Quad Tree.

10 Write a java program to traverse a graph using breadth first search.

11 Write a java program to traverse a graph using depth first search.

12 Write a java program for all pair shortest path.

13 Write a java program to insert or delete in Trie data structure.


Experiment :1
AIM: Write a java program to implement stack operation using linked list implementation of stack.
Program Code:
class Node {
int data;
Node next;
}

class Stack {
Node top;

public boolean isEmpty() {


return top == null;
}

public void push(int item) {


Node oldTop = top;
top = new Node();
top.data = item;
top.next = oldTop;
}

public int pop() {


if (isEmpty()) {
throw new RuntimeException("Stack is empty");
}
int item = top.data;
top = top.next;
return item;
}

public int peek() {


if (isEmpty()) {
throw new RuntimeException("Stack is empty");
}
return top.data;
}
}

public class Main {


public static void main(String[] args) {
Stack stack = new Stack();
System.out.println(stack.isEmpty()); // Output: true

stack.push(10);
stack.push(20);
stack.push(30);
System.out.println(stack.isEmpty()); // Output: false

System.out.println(stack.peek()); // Output: 30
System.out.println(stack.pop()); // Output: 30
System.out.println(stack.peek()); // Output: 20

System.out.println(stack.isEmpty()); // Output: false


}
}
Experiment :2
AIM: Write a java program to implement tower of Hanoi.
Program Code:
public class Main {

public static void main(String[] args) {


int n = 4;
TowerOfHanoi(n, 'A', 'C', 'B');
}

public static void TowerOfHanoi(int n, char from, char to, char aux) {
if (n == 1) {
System.out.println("Move disk 1 from " + from + " to " + to);
return;
}
TowerOfHanoi(n - 1, from, aux, to);
System.out.println("Move disk " + n + " from " + from + " to " + to);
TowerOfHanoi(n - 1, aux, to, from);
}
}
Experiment : 3
AIM: write a java program to convert infix expression to postfix and evaluate it.
Program Code:
import java.util.Stack;

public class Main {

public static void main(String[] args) {


String infix = "3+5*2-8";
String postfix = infixToPostfix(infix);
System.out.println("Postfix expression: " + postfix);
System.out.println("Evaluation of postfix expression: " + evaluatePostfix(postfix));
}

public static String infixToPostfix(String infix) {


StringBuilder postfix = new StringBuilder();
Stack<Character> stack = new Stack<>();

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


if (Character.isLetterOrDigit(c)) {
postfix.append(c);
} else if (c == '(') {
stack.push(c);
} else if (c == ')') {
while (!stack.isEmpty() && stack.peek() != '(') {
postfix.append(stack.pop());
}
stack.pop(); // Remove '(' from stack
} else {
while (!stack.isEmpty() && getPrecedence(c) <= getPrecedence(stack.peek())) {
postfix.append(stack.pop());
}
stack.push(c);
}
}

while (!stack.isEmpty()) {
postfix.append(stack.pop());
}

return postfix.toString();
}

public static int evaluatePostfix(String postfix) {


Stack<Integer> stack = new Stack<>();

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


if (Character.isLetterOrDigit(c)) {
stack.push(c - '0');
} else {
int operand2 = stack.pop();
int operand1 = stack.pop();
switch (c) {
case '+':
stack.push(operand1 + operand2);
break;
case '-':
stack.push(operand1 - operand2);
break;
case '*':
stack.push(operand1 * operand2);
break;
case '/':
stack.push(operand1 / operand2);
break;
}
}
}

return stack.pop();
}

public static int getPrecedence(char operator) {


switch (operator) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
default:
return -1;
}
}
}
Experiment : 4
AIM: Write a program to implement queue operation using linked list implementation.
Program Code:
import java.util.LinkedList;

public class Main {

public static void main(String[] args) {


Queue<Integer> queue = new Queue<>();

queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);

System.out.println("Front element of queue: " + queue.front());

queue.dequeue();

System.out.println("Front element of queue after dequeue operation: " + queue.front());


}
}

class Node<T> {
T data;
Node<T> next;

public Node(T data) {


this.data = data;
}
}

class Queue<T> {
Node<T> front;
Node<T> rear;

public Queue() {
front = rear = null;
}

public boolean isEmpty() {


return front == null;
}

public void enqueue(T item) {


Node<T> newNode = new Node<>(item);

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

rear.next = newNode;
rear = newNode;
}

public T dequeue() {
if (isEmpty()) {
return null;
}

T item = front.data;
front = front.next;

if (front == null) {
rear = null;
}
return item;
}

public T front() {
if (isEmpty()) {
return null;
}

return front.data;
}
}
Experiment : 5
AIM: Write a java program to implement Binary search Tree.
Program Code:
import java.util.LinkedList;

class Node {
int data;
Node left, right;

public Node(int item) {


data = item;
left = right = null;
}
}

class BinaryTree {
Node root;

public BinaryTree() {
root = null;
}

public void insert(int data) {


root = insertRecursive(root, data);
}

public Node insertRecursive(Node current, int data) {


if (current == null) {
return new Node(data);
}

if (data < current.data) {


current.left = insertRecursive(current.left, data);
} else if (data > current.data) {
current.right = insertRecursive(current.right, data);
}

return current;
}

public void inorderTraversal(Node node) {


if (node != null) {
inorderTraversal(node.left);
System.out.print(node.data + " ");
inorderTraversal(node.right);
}
}

public Node search(int data) {


return searchRecursive(root, data);
}

public Node searchRecursive(Node current, int data) {


if (current == null || current.data == data) {
return current;
}

if (data < current.data) {


return searchRecursive(current.left, data);
}

return searchRecursive(current.right, data);


}

public void delete(int data) {


root = deleteRecursive(root, data);
}
public Node deleteRecursive(Node current, int data) {
if (current == null) {
return null;
}

if (data == current.data) {
if (current.left == null && current.right == null) {
return null;
}

if (current.right == null) {
return current.left;
}

if (current.left == null) {
return current.right;
}

Node temp = minValueNode(current.right);


current.data = temp.data;
current.right = deleteRecursive(current.right, temp.data);
return current;
}

if (data < current.data) {


current.left = deleteRecursive(current.left, data);
} else {
current.right = deleteRecursive(current.right, data);
}

return current;
}
public Node minValueNode(Node node) {
Node current = node;

while (current.left != null) {


current = current.left;
}

return current;
}
}

public class Main {

public static void main(String[] args) {


BinaryTree tree = new BinaryTree();

tree.insert(50);
tree.insert(30);
tree.insert(20);
tree.insert(40);
tree.insert(70);
tree.insert(60);
tree.insert(80);

System.out.println("Inorder traversal of the given binary search tree: ");


tree.inorderTraversal(tree.root);

System.out.println("\nSearch 40: " + (tree.search(40) != null ? "Found" : "Not Found"));


System.out.println("Search 100: " + (tree.search(100) != null ? "Found" : "Not Found"));

tree.delete(20);
System.out.println("\nInorder traversal of the modified binary search tree: ");
tree.inorderTraversal(tree.root);
}
}
Experiment : 6
AIM: Write a java program to construct binary tree using given tree traversal
Program Code:
import java.util.HashMap;

class Node {
int data;
Node left, right;

public Node(int item) {


data = item;
left = right = null;
}
}

class BinaryTree {
int preIndex = 0;

HashMap<Integer, Integer> hMap = new HashMap<>();

public Node buildTree(int in[], int pre[], int n) {


if (n == 0) {
return null;
}

Node tNode = new Node(pre[preIndex++]);

if (n == 1) {
return tNode;
}

int inIndex = hMap.get(tNode.data);


tNode.left = buildTree(in, pre, inIndex - hMap.get(Integer.MIN_VALUE));

tNode.right = buildTree(in, pre, n - inIndex - 1);

return tNode;
}
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();

int in[] = {4, 2, 5, 1, 3};


int pre[] = {1, 2, 4, 5, 3};

int n = in.length;

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


tree.hMap.put(in[i], i);
}

tree.hMap.put(Integer.MIN_VALUE, -1);

Node root = tree.buildTree(in, pre, n);

System.out.println("Inorder traversal of the given binary tree: ");


tree.printInorder(root);
}
void printInorder(Node node) {
if (node == null) {
return;
}
printInorder(node.left);
System.out.print(node.data + " ");
printInorder(node.right);
}
Experiment: 7
AIM: Write a program for B+ tree
Program Code:
import java.util.TreeMap;

public class TreeMapExample {

public static void main(String[] args) {

TreeMap<Integer, String> map = new TreeMap<>();

// Add elements using put method


map.put(5, "Five");
map.put(2, "Two");
map.put(10, "Ten");
map.put(1, "One");
map.put(8, "Eight");

// Print the elements of TreeMap using for each loop


System.out.println("The keys are: ");
for (Integer key : map.keySet()) {
System.out.println(key);
}

System.out.println("The values are: ");


for (String value : map.values()) {
System.out.println(value);
}
}
}
Experiment : 8
AIM: Write a java program to implement AVL tree.
Program Code:
class Node {
int key, height;
Node left, right;

Node(int d) {
key = d;
height = 1;
}
}

class AVLTree {
Node root;

int height(Node N) {
if (N == null)
return 0;
return N.height;
}

int max(int a, int b) {


return (a > b) ? a : b;
}

Node rightRotate(Node y) {
Node x = y.left;
Node T2 = x.right;

x.right = y;
y.left = T2;
y.height = max(height(y.left), height(y.right)) + 1;
x.height = max(height(x.left), height(x.right)) + 1;

return x;
}

Node leftRotate(Node x) {
Node y = x.right;
Node T2 = y.left;

y.left = x;
x.right = T2;

x.height = max(height(x.left), height(x.right)) + 1;


y.height = max(height(y.left), height(y.right)) + 1;

return y;
}

int getBalance(Node N) {
if (N == null)
return 0;

return height(N.left) - height(N.right);


}

Node insert(Node node, int key) {


if (node == null)
return (new Node(key));

if (key < node.key)


node.left = insert(node.left, key);
else if (key > node.key)
node.right = insert(node.right, key);
else
return node;

node.height = 1 + max(height(node.left),
height(node.right));

int balance = getBalance(node);

if (balance > 1 && key < node.left.key)


return rightRotate(node);

if (balance < -1 && key > node.right.key)


return leftRotate(node);

if (balance > 1 && key > node.left.key) {


node.left = leftRotate(node.left);
return rightRotate(node);
}

if (balance < -1 && key < node.right.key) {


node.right = rightRotate(node.right);
return leftRotate(node);
}

return node;
}

void preOrder(Node node) {


if (node != null) {
System.out.print(node.key + " ");
preOrder(node.left);
preOrder(node.right);
}
}
void insert(int key) {
root = insert(root, key);
}

void displayTree() {
preOrder(root);
}
}

public class Main {


public static void main(String[] args) {
AVLTree tree = new AVLTree();

tree.insert(10);
tree.insert(20);
tree.insert(30);
tree.insert(40);
tree.insert(50);

tree.displayTree();
}
}
Experiment : 9
AIM: Write a java program to implement Quad Tree.
Program Code:
class Point {
int x, y;

Point(int x, int y) {
this.x = x;
this.y = y;
}
}

class Node {
Point point;
Node topLeft, topRight, bottomLeft, bottomRight;

Node(Point point) {
this.point = point;
topLeft = topRight = bottomLeft = bottomRight = null;
}
}

class QuadTree {
Node root;
int capacity;

public QuadTree(int capacity) {


this.capacity = capacity;
root = null;
}

boolean isLeaf(Node node) {


return node.topLeft == null && node.topRight == null && node.bottomLeft == null &&
node.bottomRight == null;
}

void insert(Node node, Point point) {


if (node == null) {
node = new Node(point);
return;
}

if (isLeaf(node)) {
if (node.point == null) {
node.point = point;
} else {
if (point.x < node.point.x) {
if (point.y < node.point.y) {
node.topLeft = new Node(point);
} else {
node.bottomLeft = new Node(point);
}
} else {
if (point.y < node.point.y) {
node.topRight = new Node(point);
} else {
node.bottomRight = new Node(point);
}
}
}
} else {
if (point.x < node.point.x) {
if (point.y < node.point.y) {
insert(node.topLeft, point);
} else {
insert(node.bottomLeft, point);
}
} else {
if (point.y < node.point.y) {
insert(node.topRight, point);
} else {
insert(node.bottomRight, point);
}
}
}
}

public void insert(Point point) {


if (root == null) {
root = new Node(point);
} else {
insert(root, point);
}
}
}

public class Main {


public static void main(String[] args) {
QuadTree tree = new QuadTree(4);

tree.insert(new Point(2, 3));


tree.insert(new Point(3, 2));
tree.insert(new Point(4, 4));
tree.insert(new Point(5, 5));

// Print tree
}
}
Experiment : 10
AIM : Write a java program to traverse a graph using breadth first search.
Program Code:
import java.util.*;

class Graph {
private int vertices;
private LinkedList<Integer>[] adjacencyList;

public Graph(int vertices) {


this.vertices = vertices;
adjacencyList = new LinkedList[vertices];

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


adjacencyList[i] = new LinkedList<>();
}
}

public void addEdge(int source, int destination) {


adjacencyList[source].add(destination);
}

public void BFS(int start) {


boolean[] visited = new boolean[vertices];
Queue<Integer> queue = new LinkedList<>();
visited[start] = true;
queue.add(start);

while (!queue.isEmpty()) {
int vertex = queue.poll();
System.out.print(vertex + " ");

Iterator<Integer> iterator = adjacencyList[vertex].listIterator();


while (iterator.hasNext()) {
int adjacentVertex = iterator.next();
if (!visited[adjacentVertex]) {
queue.add(adjacentVertex);
visited[adjacentVertex] = true;
}
}
}
}
}

public class Main {


public static void main(String[] args) {
Graph graph = new Graph(4);
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 2);
graph.addEdge(2, 3);

System.out.println("Breadth First Search (starting from vertex 0):");


graph.BFS(0);
}
}
Experiment : 11
AIM: Write a java program to traverse a graph using depth first search.
Program Code:
import java.util.*;

class Graph {
private int vertices;
private LinkedList<Integer>[] adjacencyList;

public Graph(int vertices) {


this.vertices = vertices;
adjacencyList = new LinkedList[vertices];

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


adjacencyList[i] = new LinkedList<>();
}
}

public void addEdge(int source, int destination) {


adjacencyList[source].add(destination);
}

public void DFS(int start) {


boolean[] visited = new boolean[vertices];
DFSUtil(start, visited);
}

private void DFSUtil(int vertex, boolean[] visited) {


visited[vertex] = true;
System.out.print(vertex + " ");

Iterator<Integer> iterator = adjacencyList[vertex].listIterator();


while (iterator.hasNext()) {
int adjacentVertex = iterator.next();
if (!visited[adjacentVertex]) {
DFSUtil(adjacentVertex, visited);
}
}
}
}

public class Main {


public static void main(String[] args) {
Graph graph = new Graph(4);
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 2);
graph.addEdge(2, 3);

System.out.println("Depth First Search (starting from vertex 0):");


graph.DFS(0);
}
}
Experiment : 12
AIM: Write a java program for all pair shortest path.
Program Code:
import java.util.*;

class Graph {
private int vertices;
private LinkedList<Pair<Integer, Integer>>[] adjacencyList;

public Graph(int vertices) {


this.vertices = vertices;
adjacencyList = new LinkedList[vertices];

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


adjacencyList[i] = new LinkedList<>();
}
}

public void addEdge(int source, int destination, int weight) {


adjacencyList[source].add(new Pair<>(destination, weight));
}

public int[][] FloydWarshall() {


int[][] dist = new int[vertices][vertices];

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


for (int j = 0; j < vertices; j++) {
if (i == j) {
dist[i][j] = 0;
} else {
dist[i][j] = Integer.MAX_VALUE;
}
}
}

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


for (Pair<Integer, Integer> pair : adjacencyList[i]) {
dist[i][pair.first] = pair.second;
}
}

for (int k = 0; k < vertices; k++) {


for (int i = 0; i < vertices; i++) {
for (int j = 0; j < vertices; j++) {
if (dist[i][k] + dist[k][j] < dist[i][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}

return dist;
}
}

public class Main {


public static void main(String[] args) {
Graph graph = new Graph(4);
graph.addEdge(0, 1, 10);
graph.addEdge(0, 2, 5);
graph.addEdge(1, 2, 2);
graph.addEdge(2, 3, 1);

int[][] shortestPaths = graph.FloydWarshall();

System.out.println("Shortest Path Matrix:");


for (int i = 0; i < shortestPaths.length; i++) {
for (int j = 0; j < shortestPaths[i].length; j++) {
System.out.print(shortestPaths[i][j] + " ");
}
System.out.println();
}
}
}
Experiment : 13
AIM: Write a java program to insert or delete in Trie data structure.
Program Code:
import java.util.*;

class TrieNode {
public char value;
public HashMap<Character, TrieNode> children;
public boolean isEndOfWord;

public TrieNode(char value) {


this.value = value;
this.children = new HashMap<>();
this.isEndOfWord = false;
}
}

class Trie {
private TrieNode root;

public Trie() {
root = new TrieNode(' ');
}

public void insert(String word) {


TrieNode currentNode = root;

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


char ch = word.charAt(i);

if (!currentNode.children.containsKey(ch)) {
currentNode.children.put(ch, new TrieNode(ch));
}
currentNode = currentNode.children.get(ch);
}

currentNode.isEndOfWord = true;
}

public boolean search(String word) {


TrieNode currentNode = root;

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


char ch = word.charAt(i);

if (!currentNode.children.containsKey(ch)) {
return false;
}

currentNode = currentNode.children.get(ch);
}

return currentNode != null && currentNode.isEndOfWord;


}

public void delete(String word) {


delete(root, word, 0);
}

private boolean delete(TrieNode currentNode, String word, int index) {


if (index == word.length()) {
if (!currentNode.isEndOfWord) {
return false;
}

currentNode.isEndOfWord = false;
return currentNode.children.size() == 0;
}

char ch = word.charAt(index);
TrieNode node = currentNode.children.get(ch);

if (node == null) {
return false;
}

boolean shouldDeleteCurrentNode = delete(node, word, index + 1) && !node.isEndOfWord;

if (shouldDeleteCurrentNode) {
currentNode.children.remove(ch);
return currentNode.children.size() == 0;
}

return false;
}
}

public class Main {


public static void main(String[] args) {
Trie trie = new Trie();
trie.insert("apple");
trie.insert("app");
trie.insert("apples");

System.out.println(trie.search("apple")); // Output: true


System.out.println(trie.search("app")); // Output: true
System.out.println(trie.search("apples")); // Output: true

trie.delete("app");
System.out.println(trie.search("apple")); // Output: true
System.out.println(trie.search("app")); // Output: false
System.out.println(trie.search("apples")); // Output: true
}
}

You might also like