0% found this document useful (0 votes)
4 views

MODULE 2

Uploaded by

rohithlaveti1822
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

MODULE 2

Uploaded by

rohithlaveti1822
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

MODULE 2

LINKED LIST

Linked list

o Linked List can be defined as collection of objects called nodes that are randomly
stored in the memory.
o A node contains two fields i.e. data stored at that particular address and the pointer
which contains the address of the next node in the memory.
o The last node of the list contains pointer to the null.

Uses of Linked List

o The list is not required to be contiguously present in the memory. The node can reside
anywhere in the memory and linked together to make a list. This achieves optimized
utilization of space.
o list size is limited to the memory size and doesn't need to be declared in advance.
o Empty node cannot be present in the linked list.
o We can store values of primitive types or objects in the singly linked list.

Why use linked list over array?

Till now, we were using array data structure to organize the group of elements that are to be
stored individually in the memory. However, Array has several advantages and
disadvantages which must be known in order to decide the data structure which will be used
throughout the program.

Array contains following limitations:

1. The size of array must be known in advance before using it in the program.
2. Increasing size of the array is a time taking process. It is almost impossible to expand
the size of the array at run time.
3. All the elements in the array need to be contiguously stored in the memory. Inserting
any element in the array needs shifting of all its predecessors.
Linked list is the data structure which can overcome all the limitations of an array. Using
linked list is useful because,

1. It allocates the memory dynamically. All the nodes of linked list are non-contiguously
stored in the memory and linked together with the help of pointers.
2. Sizing is no longer a problem since we do not need to define its size at the time of
declaration. List grows as per the program's demand and limited to the available
memory space.

Types of Linked Lists

There are majorly 3 types of linked lists in the data structures that can be implemented. And
that is –

 Singly Linked List.


 Doubly Linked List.
 Circular Linked List.

1. SINGLY LINKED LIST

Singly Linked List is a type of linked list that is Unidirectional. It can be only one
directional.(Head Node to Tail Node).

The singly linked list is a linear data structure in which each element of the list contains a
pointer which points to the next element in the list. Each element in the singly linked list is
called a node. Each node has two components: data and a pointer next which points to the
next node in the list. The first node of the list is called as head, and the last node of the list is
called a tail. The last node of the list contains a pointer to the null. Each node in the list can
be accessed linearly by traversing through the list from head to tail.

Basic terminologies of singly linked list:

 First node is called as head.


 Last node is called as tail.
 Last node compulsory have a null pointer.
How to create a Node:

Node nodename =new Node;

How to assign the value of Node:

nodename.data=value;

How to link thee head Node to tail Node:

Currentnodename.next = Nextnodename;

Basic structure of singly linked list:

public class Node


{
int data;
Node next;
}
Traversing in singly linked list

Traversing is the most common operation that is performed in almost every scenario of
singly linked list. Traversing means visiting each node of the list once in order to perform
some operation on that. This will be done by using the following statements.

Static void traversing(Node head)


{
While(head != null)
{
System.out.print(head.data + “ ”);
Head = head.next;
}
}

Creation and traversal of singly linked list:

Program:

public class single


{
static class Node
{
int data;
Node next;
};
static void PrintList(Node n)
{
while(n!=null)
{
System.out.println(n.data+"");
n=n.next;
}
}
public static void main(String args[])
{

//creations of node:
Node head=new Node();
Node second=new Node();
Node third=new Node();
Node fourth=new Node();
Node fifth=new Node();
//assign the value
head.data=1;
second.data=2;
third.data=3;
fourth.data=4;
fifth.data=5;

//link the nodes


head.next=second;
second.next=third;
third.next=fourth;
fourth.next=fifth;
fifth.next=null;
PrintList(head);
}
}
Output:
1
2
3
4
5
Singly-linked list Removal (deletion) operation.

Implementation

import java.util.Scanner;

public class delete


{
static class Node
{
int data;
Node next;
};

static void deletelist(Node n,int key)


{
Node temp=n;
Node data=null;

// If the key to be deleted is the head node


if(temp!=null && temp.data==key)
{
n=temp.next;
System.out.println("Head Node is changed");
}

// Search for the key to be deleted, keep track of the previous node
while(temp!=null && temp.data!=key)
{
data=temp;
temp=temp.next;
}

// If the key was not found in the list


if(temp==null)
{
System.out.print("No value");
}

// Unlink the node from the linked list


data.next=temp.next;
}

static void Printlist(Node n)


{
while(n!=null)
{
System.out.print(n.data);
n=n.next;
}
}

public static void main(String args[])


{
try (Scanner in = new Scanner(System.in))
{
Node head=new Node();
Node second=new Node();
Node third=new Node();
Node fourth=new Node();
Node fifth=new Node();

//assign the value

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


head.data=in.nextInt();
second.data=in.nextInt();
third.data=in.nextInt();
fourth.data=in.nextInt();
fifth.data=in.nextInt();
//link the nodes

head.next=second;
second.next=third;
third.next=fourth;
fourth.next=fifth;
fifth.next=null;

System.out.println("Original Linked List:");


printlist(head);

System.out.println("Enter the element to delete:");


int m = in.nextInt();

deleteNode(head, m);

System.out.println("Linked List after deleting the element:");


printlist(head);
}
}
}

2) DOUBLY LINKED LIST


A doubly linked list is a data structure in which each node has two pointers: one
pointing to the next node and another pointing to the previous node. This dual-linking allows
for traversal in both forward and backward directions.

 Link − Each Link of a linked list can store a data called an element.
 Next − Each Link of a linked list contain a link to next link called Next.
 Prev − Each Link of a linked list contain a link to previous link called Prev.
Basic Operations
Following are the basic operations supported by an list.
 Insertion − add an element at the list.
 Deletion − delete an element at the list.
 Display forward − displaying complete list in forward manner.
 Display backward − displaying complete list in backward manner.

Basic structure of a singly linked list

static class Node


{
int data; // Data
Node next; // Address
Node pre; //Address
};
Basic terminologies of singly linked list:

 First node is called as head.


 Last node is called as tail.
 Last node compulsory have a null pointer.

How to create a Node:

Node nodename =new Node;

How to assign the value of Node:

nodename.data=value;

How to link the head Node to tail Node:

Currentnodename.next = Nextnodename;

How to link the tail Node to head Node:

Currentnodename.prev = Previousnodename;

Basic structure of singly linked list:


public class Node
{
int data;
Node next;
Node prev;
}

Traverse In a Doubly Linked List

To traverse in a doubly linked list, we will start from the head node and follow the
next reference until we reach the end of the list similarly, we can also start from the tail node
and follow the prev until we reach the head of the node.

Forward Traversing:

Static void traversing(Node tail)


{
While(tail != null)
{
System.out.print(tail.data + “ ”);
tail = tail.next;
}
}

Backward Traversal:

Static void traversing(Node tail)


{
While(tail != null)
{
System.out.print(tail.data + “ ”);
tail = tail.pre;
}
}
Creation and traversal of doubly linked list:

Program:
public class doubly
{
static class Node
{
int data;
Node next;
Node prev;
}
static void Printnext(Node n)
{

while(n!=null)
{
System.out.println(n.data);
n=n.next;
}
}
static void Printprev(Node n)
{

while(n!=null)
{
System.out.println(n.data);
n=n.prev;
}
}
public static void main(String args[])
{
//Node Creations
Node head=new Node();
Node second=new Node();
Node tail=new Node();

//Assign the data


head.data=10;
second.data=20;
tail.data=30;

//Link the current Node


head.next=second;
second.next=tail;
tail.next=null;

tail.prev=second;
second.prev=head;
head.prev=null;

System.out.println("Head Node to Tail Node");


Printnext(head);
System.out.println("Tail Node to Head Node");
Printprev(tail);
}

}
Output:
Head Node to Tail Node
10
20
30
Tail Node to Head Node
30
20
10

DELETION IN nth POSITION DOUBLY LINKED LIST THE


 deleteNode method takes the head of the list and a reference to the node to delete as
parameters.
 It updates the next and pre references of the nodes surrounding the node to delete,
effectively removing it from the list.
 Special handling is included to update the head reference if the node to delete is the
head of the list.

public class delete


{
static class Node
{
int data;
Node next;
Node pre;
}

static void print_Forward(Node myPrg)


{
System.out.print("[ ");
while(myPrg != null)
{
System.out.print(myPrg.data+" ");
myPrg = myPrg.next;
}
System.out.print("]");
}

static void print_Backward(Node myPrg)


{
System.out.print("[ ");
while(myPrg != null)
{
System.out.print(myPrg.data+" ");
myPrg = myPrg.pre;
}
System.out.print("]");
}

// Method to delete the first node with a given data value


static Node deleteNodeByValue(Node head, int valueToDelete)
{
if (head == null)
return head;

Node current = head;

// Traverse the list to find the node with the specified data value
while (current != null && current.data != valueToDelete)
current = current.next;

// If the node with the value is found, delete it


if (current != null)
{
// Update the next reference of the previous node
if (current.pre != null)
current.pre.next = current.next;

// Update the previous reference of the next node


if (current.next != null)
current.next.pre = current.pre;

// If the node to delete is the head node, update the head reference
if (current == head)
head = current.next;

// Set the next and previous references of the node to delete to null
current.next = null;
current.pre = null;
}

return head;
}

public static void main(String[] args)


{
Node head = new Node();
Node two = new Node();
Node three = new Node();
Node four = new Node();

head.data = 10;
two.data = 20;
three.data = 30;
four.data = 40;

head.next = two;
two.next = three;
three.next = four;
four.next = null;

head.pre = null;
two.pre = head;
three.pre = two;
four.pre = three;

// Print the elements of the linked list in forward order


print_Forward(head);

// Print the elements of the linked list in backward order


print_Backward(four);
// Delete a node with a specific value (e.g., 20)
head = deleteNodeByValue(head, 20);

// Print the updated linked list


System.out.println("\nLinked List after deletion:");
print_Forward(head);
}
}

Output:

// Print the linked list in forward order


[10 20 30 40]
// Print the linked list in backward order
[40 30 20 10]
// Print the updated linked list
[10 30 40]

3) CIRCULAR LINKED LIST


What is Circular linked list?

The circular linked list is a linked list where all nodes are connected to form a circle. In a circular
linked list, the first node and the last node are connected to each other which form a circle. There is
no NULL at the end.

Terminologies of Circular liked list:

 First node is called as head.


 Last node is called as tail.
 Circular linked list does not have any null pointer.

There are generally two types of circular linked lists:

1. Circular singly linked list


2. Circular doubly linked list
1) Circular singly linked list:

Circular Singly Linked List has properties of both singly linked list and circular linked list. In a
Circular Singly linked list, the last node of the list contains a pointer to the first node of the list. We
traverse the circular singly linked list until we reach the same node where we started. The circular
singly linked list has no beginning or end. No null value is present in the next part of any of the
nodes.

Basic Structure of Circular Singly Linked List:

public class Node


{
int data;
Node next;
public Node(int data)
{
this.data = data;
this.next = null;
}
}

Example of Circular singly linked list:


The above Circular singly linked list can be represented as:

// Define the Node class


class Node
{
int value;
Node next;

public Node(int value)

{
this.value = value;
}
}

// Initialize the Nodes.

Node one = new Node(3);


Node two = new Node(5);
Node three = new Node(9);
// Connect nodes
one.next = two;
two.next = three;
three.next = one;

Program:

class Node
{
int data;
Node next;

public Node(int data)


{
this.data = data;
this.next = null;
}
}
class CircularSinglyLinkedList
{
Node head;
Node tail;

public CircularSinglyLinkedList()
{
this.head = null;
this.tail = null;
}

public void addToEmptyList(int data)


{
Node hello = new Node(data);
if (head == null)
{
head = hello;
tail = hello;
hello.next = head;
}
}
public void addAtBeginning(int data) {
Node hello = new Node(data);
if (head == null)
{
addToEmptyList(data);
}
else
{
hello.next = head;
tail.next = hello;
head = hello;
}
}

public void addAtEnd(int data)


{
Node hello = new Node(data);
if (head == null)
{
addToEmptyList(data);
}
else
{
hello.next = head;
tail.next = hello;
tail = hello;
}
}

public void display()


{
if (head == null)
{
System.out.println("The list is empty.");
return;
}
Node n = head;
do
{
System.out.print(n.data + " ");
n = n.next;
} while (n != head);
System.out.println();
}
}
public class Main
{
public static void main(String[] args)
{
CircularSinglyLinkedList list = new CircularSinglyLinkedList();
list.display();
// Add at beginning
list.addAtBeginning(10);
list.addAtBeginning(20);
list.display();
//Add at ending
list.addAtEnd(30);
list.addAtEnd(40);
list.display();
}
}

Output:

The list is empty.


10
20, 10
20, 10, 30, 40
2)Circular doubly linked list:

Circular Doubly Linked List has properties of both doubly linked list and circular linked list in
which two consecutive elements are linked or connected by the previous and next pointer and the
last node points to the first node by the next pointer and also the first node points to the last node by
the previous pointer.

Basic Structure of Circular Doubly Linked List:

public class Node


{
int data;
Node next;
Node prev;
public Node(int data)
{
this.data = data;
this.next = null;
this.prev=null;
}
}
Program:

class Node
{
int data;
Node next;
Node prev;

public Node(int data)


{
this.data = data;
this.next = null;
this.prev = null;
}
}
class CircularDoublyLinkedList
{
Node head;
Node tail;
public CircularDoublyLinkedList()
{
this.head = null;
this.tail = null;
}
public void addToEmptyList(int data) {
Node hello = new Node(data);
if (head == null)
{
head = hello;
tail = hello;
hello.next = head;
hello.prev = head;
}
}
public void addAtBeginning(int data)
{
Node hello = new Node(data);
if (head == null)
{
addToEmptyList(data);
}
else
{
tail.next = hello;
hello.next = head;

head.prev = hello;
hello.prev = tail;

head = hello;
}
}

public void addAtEnd(int data) {


Node hello = new Node(data);
if (head == null)
{
addToEmptyList(data);
}
else
{
tail.next = hello;
hello.next = head;
head.prev = hello;
hello.prev = tail;

tail = hello;
}
}

public void display()


{
if (head == null)
{
System.out.println("The list is empty.");
return;
}

Node n = head;
do
{
System.out.print(n.data + " ");
n = n.next;
} while (n != head);
System.out.println();
}
}

public class CircularDoublyLinkedListDemo {


public static void main(String[] args) {
CircularDoublyLinkedList list = new CircularDoublyLinkedList();

list.display();
// Add at the beginning
list.addAtBeginning(10);
list.display();
list.addAtBeginning(20);
list.display();
// Add at the end
list.addAtEnd(30);
list.display();
list.addAtEnd(40);
list.display();
}
}

Output:

The list is empty.


10
20 10
20 10 30
20 10 30 40
IMPLEMENT A STACK USING SINGLY LINKED LIST:
// A Linked List Node
class Node
{
int data; // integer data
Node next; // pointer to the next node
}
class Stack
{
private Node top;
private int nodesCount;
public Stack()
{
this.top = null;
this.nodesCount = 0;
}

// Utility function to add an element `x` to the stack


public void push(int x) // insert at the beginning
{
// allocate a new node in a heap
Node node = new Node();

// check if stack (heap) is full. Then inserting an element would


// lead to stack overflow
if (node == null)
{
System.out.println("Heap Overflow");
return;
}

System.out.println("Inserting " + x);

// set data in the allocated node


node.data = x;

// set the .next pointer of the new node to point to the current
// top node of the list
node.next = top;

// update top pointer


top = node;

// increase stack's size by 1


this.nodesCount += 1;
}

// Utility function to check if the stack is empty or not


public boolean isEmpty() {
return top == null;
}
// Utility function to return the top element of the stack
public int peek()
{
// check for an empty stack
if (isEmpty()) {
System.out.println("The stack is empty");
System.exit(-1);
}
return top.data;
}

// Utility function to pop a top element from the stack


public int pop() // remove at the beginning
{
// check for stack underflow
if (isEmpty())
{
System.out.println("Stack Underflow");
System.exit(-1);
}

// take note of the top node's data


int top = peek();

System.out.println("Removing " + top);

// decrease stack's size by 1


this.nodesCount -= 1;

// update the top pointer to point to the next node


this.top = (this.top).next;

return top;
}

// Utility function to return the size of the stack


public int size() {
return this.nodesCount;
}
}
class Main
{
public static void main(String[] args)
{
Stack stack = new Stack();

stack.push(1);
stack.push(2);
stack.push(3);

System.out.println("The top element is " + stack.peek());


stack.pop();
stack.pop();
stack.pop();

if (stack.isEmpty()) {
System.out.println("The stack is empty");
}
else {
System.out.println("The stack is not empty");
}
}
}

Output:

Inserting 1
Inserting 2
Inserting 3
The top element is 3
Removing 3
Removing 2
Removing 1
The stack is empty

IMPLEMENT A QUQUE USING SINGLY LINKED LIST:

import java.util.*;
public class Main
{
private Node front, rear;
private int s; // number of items

//class to define linked node


private class Node
{
int data;
Node next;
}

public Main ()
{
front = null;
rear = null;
s = 0;
}

public boolean isEmpty ()


{
return (s == 0);
}

public void disp ()


{
if (s == 0)
{
System.out.println ("queue is empty");
return;
}
Node temp = front;
while (temp != null)
{
System.out.print (" " + temp.data);
temp = temp.next;
}

}
//to Remove item
public void dequeue ()
{
int data = front.data;
front = front.next;
if (isEmpty ())
{
rear = null;
}
s--;

//to Add data .


public void enqueue (int data)
{
Node old = rear;
rear = new Node ();
rear.data = data;
rear.next = null;
if (isEmpty ())
{
front = rear;
}
else
{
old.next = rear;
}
s++;
System.out.println (data + " added to the queue");
}

public static void main (String args[])


{

Main queue = new Main ();


queue.enqueue (1);
queue.enqueue (2);
queue.enqueue (3);
queue.enqueue (4);
System.out.println ("Original queue :");
queue.disp ();
System.out.println ();

queue.dequeue ();
queue.dequeue ();
System.out.println ("Queue after dequeue");
queue.disp ();
}
}

Output:
1 added to the queue
2 added to the queue
3 added to the queue
4 added to the queue
Original queue :
1234
Queue after dequeue
34

You might also like