You are on page 1of 6

Data Structure and Algorithms lab exam

Amit Kumar Ranjan

Q1 WAP to insert in between in doubly linked list. 


public class DoublyLinkedList {

private static class Node {

int data;

Node next;

Node prev;

public Node(int data) {

this.data = data;

private Node head;

private Node tail;

public void insertInBetween(Node node1, Node node2, int data) {

Node newNode = new Node(data);

// Set the next and previous pointers of the new node

newNode.prev = node1;

newNode.next = node2;

// Update the next and previous pointers of the surrounding nodes

node1.next = newNode;
node2.prev = newNode;

}
}

Q2 WAP to implement stack using linked list. 

public class Stack {

private static class Node {

int data;

Node next;

public Node(int data) {

this.data = data;

private Node top;

public void push(int data) {

Node newNode = new Node(data);

newNode.next = top;

top = newNode;

}
public int pop() {

if (top == null) {

throw new EmptyStackException();

int data = top.data;

top = top.next;

return data;

public int peek() {

if (top == null) {

throw new EmptyStackException();

return top.data;

public boolean isEmpty() {

return top == null;

}
}

Q3 WAP to implement quick sort. 

public class QuickSort {


public static void quickSort(int[] arr, int low, int high) {

if (low < high) {

int pivot = partition(arr, low, high);

quickSort(arr, low, pivot - 1);

quickSort(arr, pivot + 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;

}
}

Q4 WAP to do matrix multiplication.

public class MatrixMultiplication {

public static int[][] multiply(int[][] a, int[][] b) {

int rowsA = a.length;

int colsA = a[0].length;

int rowsB = b.length;

int colsB = b[0].length;

if (colsA != rowsB) {

throw new IllegalArgumentException("Cannot multiply matrices:


dimensions do not match.");

int[][] result = new int[rowsA][colsB];

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

for (int j = 0; j < colsB; j++) {

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


result[i][j] += a[i][k] * b[k][j];

return result;

}
}

You might also like