0% found this document useful (0 votes)
9 views22 pages

Unit 5

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)
9 views22 pages

Unit 5

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/ 22

Hindusthan

HindusthanCollege
Collegeof
ofEngineering
Engineering and Technology
Technology
An Autonomous Institution Affiliated to Anna University | Approved by AICTE, New Delhi
(An Autonomous
Accredited with ‘A’ GradeInstitution, Affiliated to
by NAAC | Accredited by Anna University,
NBA (ECE, MECH, Chennai)
EEE, IT & CSE)
ValleyValley
Campus,Campus,
PollachiPollachi
Highway,Highway, Coimbatore
Coimbatore 641 032.| –www.hicet.ac.in
641032

22CS3251 / OBJECT ORIENTED PROGRAMMING


USING JAVA

UNIT 5 - DATA STRUCTURE IN JAVA


Arrays-Linked list- implementation of linked list-stack-implementation of stack operations-Queue-
implementation of queue operations-Tree-Binary search tree implementation-Graphs-shortest path
algorithm using java.

1. LINKED LIST
A linked list consists of nodes where each node contains a data field and a reference(link) to the next
node in the list.

Node Structure: A node in a linked list typically consists of two components:


Data: It holds the actual value or data associated with the node.
Next Pointer: It stores the memory address (reference) of the next node in the sequence.
Head and Tail: The linked list is accessed through the head node, which points to the first node in the
list.
Types of linked lists:
There are mainly three types of linked lists:

 Single-linked list
 Double linked list
 Circular linked list
Operations on Linked Lists
Insertion: Adding a new node to a linked list involves adjusting the pointers of the existing nodes to
maintain the proper sequence. Insertion can be performed at the beginning, end, or any position within
the list
Deletion: Removing a node from a linked list requires adjusting the pointers of the neighboring nodes to
bridge the gap left by the deleted node. Deletion can be performed at the beginning, end, or any position
within the list.
Searching: Searching for a specific value in a linked list involves traversing the list from the head node
until the value is found or the end of the list is reached.

Linked list implementation


import java.io.*;
public class LinkedList
{
Node head;
static class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
public static LinkedList insert(LinkedList list, int data)
{
Node new_node = new Node(data);
if (list.head == null) {
list.head = new_node;
}
else
{
Node last = list.head;
while (last.next != null)
{
last = last.next;
}
last.next = new_node;
}
return list;
}
public static void printList(LinkedList list)
{
Node currNode = list.head;
System.out.print("LinkedList: ");
while (currNode != null)
{
System.out.print(currNode.data + " ");
currNode = currNode.next;
}
} public static void main(String[] args)
{
LinkedList list = new LinkedList();
list = insert(list, 1);
list = insert(list, 2);
list = insert(list, 3);
list = insert(list, 4);
list = insert(list, 5);
list = insert(list, 6);
list = insert(list, 7);
list = insert(list, 8);
printList(list);
}
}
Advantages of Linked Lists
 Dynamic Size: Linked lists can grow or shrink dynamically, as memory allocation is done at
runtime.
 Insertion and Deletion: Adding or removing elements from a linked list is efficient, especially for
large lists.

 Flexibility: Linked lists can be easily reorganized and modified without requiring a contiguous
block of memory.
Disadvantages of Linked Lists
 Random Access: Unlike arrays, linked lists do not allow direct access to elements by index.
Traversal is required to reach a specific node.
 Extra Memory: Linked lists require additional memory for storing the pointers, compared to
arrays.

Array Linked List

An array is collection of elements having A Linked list is a collection of nodes


same data types. that contains data and address.

The location of array elements is the Location of linked list nodes is not
continuous continuous.

Linked lists are based on dynamic


Arrays are based on static memory which
memory which means the size of the
means the size of the array is fixed.
linked list is dynamic.

Memory is allocated during compile time in Memory is allocated during run-time


arrays in a linked list
Array Linked List

Memory uses is more than array


Memory uses is lesser than linked list
because linked stores data and address
because an array only contains data.
both

In an array, Memory is not utilized in an In a linked list, Memory is utilized in


efficient way because if we create an array of an efficient way as we create new node
size 10 and we only use 5 elements then it only there is required so no memory
will be a waste of memory. will be wasted.

Linked lists are faster compared to an


Arrays are slower compared to the linked
array. It takes less time to perform
list. It takes more time to perform various
various operations like insert and
operations like insert and delete
delete

Insertion (Time Complexity):- i.)At the Insertion (Time Complexity):-i.) At


start:- O(n) ii.)At the end:- O(1) iii.)At mid:- the start:- O(1) ii.) At the end:- O(n)
O(n) iii.) At mid:- O(n)

Deletion (Time Complexity):- i.) At the Deletion (Time Complexity):- i.) At


start:- O(n) ii.) At the end:- O(1) iii.) At the start:- O(1) ii.) At the end:- O(n)
mid:- O(n) iii.) At mid:- o(n)

2. STACK
 A Stack is a linear data structure that follows the LIFO (Last-In-First-Out) principle. Stack has
one end.
 It contains only one pointer top pointer pointing to the topmost element of the stack.
 Whenever an element is added in the stack, it is added on the top of the stack, and the element
can be deleted only from the stack.
 A stack can be defined as a container in which insertion and deletion can be done from the one
end known as the top of the stack.
Operations implemented on the stack:

o push(): When we insert an element in a stack then the operation is known as a push. If the stack
is full then the overflow condition occurs.
o pop(): When we delete an element from the stack, the operation is known as a pop. If the stack
is empty means that no element exists in the stack, this state is known as an underflow state.
o isEmpty(): It determines whether the stack is empty or not.
o isFull(): It determines whether the stack is full or not.'
o peek(): It returns the element at the given position.

PUSH operation

The steps involved in the PUSH operation is given below:

o Before inserting an element in a stack, we check whether the stack is full.


o If we try to insert the element in a stack, and the stack is full, then the overflow condition occurs.
o When we initialize a stack, we set the value of top as -1 to check that the stack is empty.
o When the new element is pushed in a stack, first, the value of the top gets incremented,
i.e., top=top+1, and the element will be placed at the new position of the top.
o The elements will be inserted until we reach the max size of the stack.
POP operation

The steps involved in the POP operation is given below:

o Before deleting the element from the stack, we check whether the stack is empty.
o If we try to delete the element from the empty stack, then the underflow condition occurs.
o If the stack is not empty, we first access the element which is pointed by the top
o Once the pop operation is performed, the top is decremented by 1, i.e., top=top-1.

Stack implementation
class Stack
{
private int arr[];
private int top;
private int capacity;
Stack(int size)
{
arr = new int[size];
capacity = size;
top = -1;
}
public void push(int x)
{
if (isFull())
{
System.out.println("Stack OverFlow");
System.exit(1);
}
System.out.println("Inserting " + x);
arr[++top] = x;
}
public int pop()
{
if (isEmpty())
{
System.out.println("STACK EMPTY");
System.exit(1);
}
return arr[top--];
}
public int getSize()
{
return top + 1;
}
public Boolean isEmpty()
{
return top == -1;
}
public Boolean isFull()
{
return top == capacity - 1;
}
public void printStack()
{
for (int i = 0; i <= top; i++)
{
System.out.print(arr[i] + ", ");
}
}
}
public class Main
{
public static void main(String[] args)
{
Stack stack = new Stack(5);
stack.push(1);
stack.push(2);
stack.push(3);
System.out.print("Stack: ");
stack.printStack();
stack.pop();
System.out.println("\nAfter popping out");
stack.printStack();
}
}
Application of the Stack
 Evaluating postfix expression
 Backtracking
 To check balanced parenthesis
 Function calls and recursion

Java program to evaluate an expression entered in “postfix” form using stack:


import java.util.*;
public class Main
{
static int evaluatePostfix(String exp)
{
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < exp.length(); i++)
{
char c = exp.charAt(i);
if (Character.isDigit(c))
stack.push(c - '0');
else
{
int val1 = stack.pop();
int val2 = stack.pop();
switch (c)
{
case '+':
stack.push(val2 + val1);
break;
case '-':
stack.push(val2 - val1);
break;
case '/':
stack.push(val2 / val1);
break;
case '*':
stack.push(val2 * val1);
break;
}
}
}
return stack.pop();
}
public static void main(String[] args)
{
String exp;
Scanner in = new Scanner(System.in);
System.out.println("Enter the postfix expression: ");
exp = in.nextLine();
System.out.println("postfix evaluation: "+ evaluatePostfix(exp));
}
}

Advantages of Stack
 A Stack helps to manage the data in the ‘Last in First out’ method.
 When the variable is not used outside the function in any program, the Stack can be used.
 It allows you to control and handle memory allocation and deallocation.
 It helps to automatically clean up the objects.
Disadvantages of Stack
 It is difficult in Stack to create many objects as it increases the risk of the Stack overflow.
 It has very limited memory.
 In Stack, random access is not possible.

3. QUEUE
 Queue is referred to be as First In First Out list.
 A queue can be defined as an ordered list which enables insert operations to be performed at one
end called REAR and delete operations to be performed at another end called FRONT.
 For example, people waiting in line for a rail ticket form a queue.

Operations for Queue in Data Structure are:


 enqueue() – Insertion of elements to the queue.
 dequeue() – Removal of elements from the queue.
 peek() or front()- Acquires the data element available at the front node of the queue without
deleting it.
 rear() – This operation returns the element at the rear end without removing it.
 isFull() – Validates if the queue is full.
 isEmpty() – Checks if the queue is empty.
 size(): This operation returns the size of the queue i.e. the total number of elements it contains.
Enqueue()
Inserts an element at the end of the queue i.e. at the rear end.
The following steps should be taken to enqueue (insert) data into a queue:
 Check if the queue is full.
 If the queue is full, return overflow error and exit.
 If the queue is not full, increment the rear pointer to point to the next empty space.
 Add the data element to the queue location, where the rear is pointing.
 return success.

Dequeue()
This operation removes and returns an element that is at the front end of the queue.
The following steps are taken to perform the dequeue operation:
 Check if the queue is empty.
 If the queue is empty, return the underflow error and exit.
 If the queue is not empty, access the data where the front is pointing.
 Increment the front pointer to point to the next available data element.
 The Return success.
Queue implementation
class Queue
{
int SIZE = 5;
int items[] = new int[SIZE];
int front, rear;
Queue()
{
front = -1;
rear = -1;
}
boolean isFull()
{ if (front == 0 && rear == SIZE - 1) {
return true; }
return false;
}
boolean isEmpty()
{
if (front == -1)
return true;
else
return false;
}
void enQueue(int element)
{
if (isFull())
{
System.out.println("Queue is full");
}
else
{
if (front == -1)
{
front = 0;
}
rear++;
items[rear] = element;
System.out.println("Insert " + element);
}
}
int deQueue()
{
int element;
if (isEmpty())
{
System.out.println("Queue is empty");
return (-1);
}
else
{
element = items[front];
if (front >= rear)
{
front = -1;
rear = -1;
}
else
{
front++;
}
System.out.println( element + " Deleted");
return (element);
}
}
void display()
{
int i;
if (isEmpty())
{
System.out.println("Empty Queue");
}
else
{
System.out.println("\nFront index-> " + front);
System.out.println("Items -> ");
for (i = front; i <= rear; i++)
System.out.print(items[i] + " ");
System.out.println("\nRear index-> " + rear);
}
}
}
public class Main

{
public static void main(String[] args)
{
Queue q = new Queue();
q.deQueue();
for(int i = 1; i < 6; i ++)
{
q.enQueue(i);
}
q.enQueue(6);
q.display();
q.deQueue();
q.display();
}
}
4. BINARY SEARCH TREE
Binary Search Tree is a node-based binary tree data structure which has the following properties:

 The left subtree of a node contains only nodes with keys lesser than the node’s key.
 The right subtree of a node contains only nodes with keys greater than the node’s key.
 The left and right subtree each must also be a binary search tree.

Basic Operations:
 Insertion in Binary Search Tree
 Searching in Binary Search Tree
 Deletion in Binary Search Tree
 Binary Search Tree (BST) Traversals – Inorder, Preorder, Post Order
Binary search tree implementation
public class BinarySearchTree
{
public static class Node
{
int data;
Node left;
Node right;
public Node(int data)
{
this.data = data;
this.left = null;
this.right = null;
}
}
public Node root;
public BinarySearchTree()
{
root = null;
}
public void insert(int data) {
Node newNode = new Node(data);
if(root == null){
root = newNode;
return;
}
else {
Node current = root, parent = null;
while(true) {
parent = current;
if(data < current.data) {
current = current.left;
if(current == null) {
parent.left = newNode;
return;
}
}
else {
current = current.right;
if(current == null) {
parent.right = newNode;
return;
}
} } } }
public Node minNode(Node root) {
if (root.left != null)
return minNode(root.left);
else
return root;
}
public Node deleteNode(Node node, int value) {
if(node == null){
return null;
}
else {
if(value < node.data)
node.left = deleteNode(node.left, value);
else if(value > node.data)
node.right = deleteNode(node.right, value);
else {
if(node.left == null && node.right == null)
node = null;
else if(node.left == null) {
node = node.right;
}
else if(node.right == null) {
node = node.left;
}
else {
Node temp = minNode(node.right);
node.data = temp.data;
node.right = deleteNode(node.right, temp.data);
}
}
return node;
}
}
public void inorderTraversal(Node node) {
if(root == null){
System.out.println("Tree is empty");
return;
}
else {

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

}
}
public static void main(String[] args) {
BinarySearchTree bt = new BinarySearchTree();
bt.insert(50);
bt.insert(30);
bt.insert(70);
bt.insert(60);
bt.insert(10);
bt.insert(90);
System.out.println("Binary search tree after insertion:");
bt.inorderTraversal(bt.root);
Node deletedNode = null;
deletedNode = bt.deleteNode(bt.root, 90);
System.out.println("\nBinary search tree after deleting node 90:");
bt.inorderTraversal(bt.root);
deletedNode = bt.deleteNode(bt.root, 30);
System.out.println("\nBinary search tree after deleting node 30:");
bt.inorderTraversal(bt.root);
deletedNode = bt.deleteNode(bt.root, 50);
System.out.println("\nBinary search tree after deleting node 50:");
bt.inorderTraversal(bt.root);
}
}
5. GRAPH
A Graph is a non-linear data structure consisting of vertices and edges. The vertices are sometimes also
referred to as nodes and the edges are lines or arcs that connect any two nodes in the graph. More
formally a Graph is composed of a set of vertices( V ) and a set of edges( E ). The graph is denoted by
G(E, V).

Components of a Graph
 Vertices: Vertices are the fundamental units of the graph. Sometimes, vertices are also known
as vertex or nodes. Every node/vertex can be labeled or unlabelled.
 Edges: Edges are drawn or used to connect two nodes of the graph. It can be ordered pair of
nodes in a directed graph. Edges can connect any two nodes in any possible way. There are no
rules. Sometimes, edges are also known as arcs. Every edge can be labeled/unlabelled.
Graphs are used to solve many real-life problems. Graphs are used to represent networks. The networks
may include paths in a city or telephone network or circuit network. Graphs are also used in social
networks like linkedIn, Facebook. For example, in Facebook, each person is represented with a
vertex(or node). Each node is a structure and contains information like person id, name, gender, locale
etc.

6. SHORTEST PATH ALGORITHM


 Dijkstra’s algorithm is a popular algorithms for solving many single-source shortest path
problems having non-negative edge weight in the graphs i.e., it is to find the shortest distance
between two vertices on a graph.
 It was developed by Dutch computer scientist Edsger W. Dijkstra in 1956.
Algorithm for Dijkstra’s Algorithm:
1) Mark the source node with a current distance of 0 and the rest with infinity.
2) Set the non-visited node with the smallest current distance as the current node.
3) For each neighbor, N of the current node adds the current distance of the adjacent node with
the weight of the edge connecting 0->1. If it is smaller than the current distance of Node, set it
as the new current distance of N.
4) Mark the current node 1 as visited.
5) Go to step 2 if there are any nodes are unvisited.

Java program to implement Dijkstra’s algorithm


import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
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)
{
System.out.println("Vertex Distance from Source");
for (int i = 0; i < V; i++)
System.out.println(i + " tt " + 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 } };
Main t = new Main();
t.dijkstra(graph, 0);
}
}

You might also like