0% found this document useful (0 votes)
11 views65 pages

DS - 1

The document provides an overview of linked lists, detailing their structure and types, including singly linked lists, doubly linked lists, and circular linked lists. It explains various operations such as traversal, searching, insertion, and deletion for both singly and doubly linked lists, along with sample code implementations. The content is aimed at students studying data structures and algorithms in a computer science curriculum.

Uploaded by

Mukesh Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views65 pages

DS - 1

The document provides an overview of linked lists, detailing their structure and types, including singly linked lists, doubly linked lists, and circular linked lists. It explains various operations such as traversal, searching, insertion, and deletion for both singly and doubly linked lists, along with sample code implementations. The content is aimed at students studying data structures and algorithms in a computer science curriculum.

Uploaded by

Mukesh Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 65

AGURCHAND MANMULL JAIN COLLEGE

(A Unit of Sri. S.S. Jain Educational Society)


Meenambakkam, Chennai – 600 061

DEPARTMENT OF COMPUTER SCIENCE


B.SC COMPUTER SCIENCE
SEMESTER-IV

Data Structures and Algorithms


( 225C4A )
Linked List

• A linked list is a linear data structure which can store a


collection of elements called "nodes" connected together
through pointers.
• Linked lists nodes are not stored at a contiguous location.
• Each node contains two fields i.e. data and the pointer
which contains the address of the next node in the
memory.
• A linked list starts with a head node which points to the
first node. The last node of the list contains pointer to
the null indicating the end of the list.
Types of Linked Lists

1. Singly Linked List


Each node points to the next node.
Traversal is unidirectional (forward only).
Types of Linked Lists

2. Doubly Linked List


Each node points to both the next and previous nodes.
Allows bidirectional traversal (forward and backward).
Types of Linked Lists

3. Circular Linked List


The last node points back to the first node.
Can be singly or doubly linked.
Forms a circular structure, enabling continuous
traversal.
Singly Linked List

Singly linked list is the simplest type of linked list in which every node contains
some data and a pointer to the next node
Definition of a Node in a singly linked list
• public class Node {
• int data;
• Node next;
• // Constructor to initialize the node with data
• public Node(int data)
• {
• this.data = data;
• this.next = null;
• }
• }
Operations on Singly Linked List

• Traversal
• Searching
• Length
• Insertion:
– Insert at the beginning
– Insert at the end
– Insert at a specific position
• Deletion:
– Delete from the beginning
– Delete from the end
– Delete a specific node
Traversal

Traversal of Singly Linked List


• Traversal involves visiting each node in the linked list
and performing some operation on the data.
Step-by-step approach:
• Initialize a pointer current to the head of the list.
• Use a while loop to iterate through the list until the
current pointer reaches NULL.
• Inside the loop, print the data of the current node
and move the current pointer to the next node
public static void traverseLinkedList(Node head)
{
Node current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
Searching

• Searching in Singly Linked List


• Searching in a Singly Linked List refers to the process of
looking for a specific element or value within the
elements of the linked list.
• Step-by-step approach:
• Traverse the Linked List starting from the head.
• Check if the current node's data matches the target
value.
– If a match is found, return true.
• Otherwise, Move to the next node and repeat steps 2.
• If the end of the list is reached without finding a match,
return false.
public boolean searchLinkedList(Node head, int target)
{
while (head != null) {
if (head.data == target) {
return true;
}

head = head.next;
}
return false;
}
Length

Length of Singly Linked List


• Finding Length in Singly Linked List refers to the process of
determining the total number of nodes in a singly linked list.

Step-by-step approach:
• Initialize a counter length to 0.
• Start from the head of the list, assign it to current.
• Traverse the list:
– Increment length for each node.
– Move to the next node (current = current->next).
• Return the final value of length.

public int findLength(Node head) {
int length = 0;
Node current = head;
while (current != null) {
length++;
current = current.next;
}
return length;
}
Insertion

Insertion at the Beginning of Singly Linked List:


Step-by-step approach:
• Create a new node with the given value.
• Set the next pointer of the new node to the current
head.
• Move the head to point to the new node.
• Return the new head of the linked list.
public Node insertAtBeginning(Node head, int value)
{
Node newNode = new Node(value);
newNode.next = head;
head = newNode;
return head;
}
Insertion at the End of Singly Linked List:
Step-by-step approach:
• Create a new node with the given value.
• Check if the list is empty:
– If it is, make the new node the head and return.
• Traverse the list until the last node is reached.
• Link the new node to the current last node by setting the last
node's next pointer to the new node.
public static Node insertAtEnd(Node head, int value)
{
Node newNode = new Node(value);
if (head == null)
return newNode;
Node curr = head;
while (curr.next != null) {
curr = curr.next;
}
curr.next = newNode;
return head;
}
Insertion at a Specific Position of the Singly Linked List:
• To insert a node at a specific position, traverse the list
to the desired position, link the new node to the next
node, and update the links accordingly.
• If we encounter a NULL before reaching that node, it
means that the given position is invalid.
public static Node insertPos(Node head,
int pos, int data) Node prev = head;
int count = 1;
{
while (count < pos - 1 && prev !=
if (pos < 1) { null) {
System.out.println("Invalid prev = prev.next;
position!"); count++;
return head; }
} if (prev == null) {
if (pos == 1) { System.out.println("Invalid
position!");
Node temp = new Node(data);
return head;
temp.next = head; }
return temp; Node temp = new Node(data);
} temp.next = prev.next;
prev.next = temp;

return head;
}
Deletion
Deletion at the Beginning of Singly Linked List:
• To delete the first node, update the head to point to the
second node in the list.
Steps-by-step approach:
• Check if the head is NULL.
– If it is, return NULL (the list is empty).
• Store the current head node in a temporary variable temp.
• Move the head pointer to the next node.
• Delete the temporary node.
• Return the new head of the linked list.
• static Node removeFirstNode(Node head)
• {
• if (head == null)
• return null;
• Node temp = head;
• head = head.next;
• return head;
• }
Deletion at the End of Singly Linked List:
• To delete the last node, traverse the list until the second-to-last
node and update its next field to None.
Step-by-step approach:
• Check if the head is NULL.
– If it is, return NULL (the list is empty).
• Check if the head's next is NULL (only one node in the list).
– If true, delete the head and return NULL.
• Traverse the list to find the second last node (second_last).
• Delete the last node (the node after second_last).
• Set the next pointer of the second last node to NULL.
• Return the head of the linked list.
• Node removeLastNode(Node head)
• // Remove the last node
• {
• second_last.next = null;
• if (head == null)
• return null;
• // Return the modified list
• if (head.next == null) {
• return head;
• head = null;
• }
• return null;
• }
• Node second_last = head;
• while (second_last.next.next != null)
• second_last = second_last.next;
Deletion at a Specific Position of Singly Linked List:
• To delete a node at a specific position, traverse the list to the
desired position, update the links to bypass the node to be deleted.
Step-by-step approach:
• Check if the list is empty or the position is invalid, return if so.
• If the head needs to be deleted, update the head and delete the
node.
• Traverse to the node before the position to be deleted.
• If the position is out of range, return.
• Store the node to be deleted.
• Update the links to bypass the node.
• Delete the stored node.
• public void deleteAtPosition(Node head, int position)
• {
• if (head == null || position < 1) {
• return;
• }
• if (position == 1) {
• Node temp = head;
• head = head.next;
• temp = null;
• return;
• }
• // Traverse to the node before the position to be
• // deleted
• Node current = head;
• for (int i = 1; i < position - 1 && current != null;
• i++) {
• current = current.next;
• }
• // If the position is out of range
• if (current == null || current.next == null) {
• return;
• }
• // Store the node to be deleted
• Node temp = current.next;
• // Update the links to bypass the node to be deleted
• current.next = current.next.next;

• // Delete the node


• temp = null;
• }
Doubly Linked List

• A doubly linked list is a data structure that consists of a set of


nodes, each of which contains a value and two pointers, one
pointing to the previous node in the list and one pointing to
the next node in the list.
• This allows for efficient traversal of the list in both directions,
making it suitable for applications where
frequent insertions and deletions are required.
Representation of Doubly Linked List in Data Structure
• In a data structure, a doubly linked list is represented using nodes that have three
fields:
• Data
• A pointer to the next node (next)
• A pointer to the previous node (prev)
class Node {
int data;
Node prev;
Node next;
Node(int d) {
data = d;
prev = next = null;
}
};
Operations on Doubly Linked List

• Traversal in Doubly Linked List


• Searching in Doubly Linked List
• Finding Length of Doubly Linked List
• Insertion in Doubly Linked List:
– Insertion at the beginning of Doubly Linked List
– Insertion at the end of the Doubly Linked List
– Insertion at a specific position in Doubly Linked List
• Deletion in Doubly Linked List:
– Deletion of a node at the beginning of Doubly Linked List
– Deletion of a node at the end of Doubly Linked List
– Deletion of a node at a specific position in Doubly Linked List
Traversal in Doubly Linked List
• To Traverse the doubly list, we can use the following steps:
a. Forward Traversal:
• Initialize a pointer to the head of the linked list.
• While the pointer is not null:
– Visit the data at the current node.
– Move the pointer to the next node.
b. Backward Traversal:
• Initialize a pointer to the tail of the linked list.
• While the pointer is not null:
– Visit the data at the current node.
– Move the pointer to the previous node.
• // Define the Node class
• class Node {
• int data; // Data stored in the node
• Node next; // Pointer to the next node
• Node prev; // Pointer to the previous node
• // Constructor to initialize the node with data
• public Node(int data) {
• this.data = data;
• this.next = null;
• this.prev = null;
• }
• }
• class GfG {
• static void forwardTraversal(Node head) {
• Node curr = head;
• while (curr != null) {
• System.out.print(curr.data + " ");
• curr = curr.next;
• }
• System.out.println();
• }
• static void backwardTraversal(Node tail) {
• Node curr = tail;
• while (curr != null) {
• System.out.print(curr.data + " ");
• curr = curr.prev;
• }
• System.out.println();
• }
• public static void main(String[] args) {

• // Sample usage of the doubly linked
• // list and traversal functions
• Node head = new Node(1);
• Node second = new Node(2);
• Node third = new Node(3);

• head.next = second;
• second.prev = head;
• second.next = third;
• third.prev = second;

• System.out.println("Forward Traversal:");
• forwardTraversal(head);

• System.out.println("Backward Traversal:");
• backwardTraversal(third);
• }
• }
• static void backwardTraversal(Node tail) {
• Node curr = tail;
• // Continue until the current node is
• // null (end of the list)
• while (curr != null) {
• // Output data of the current node
• System.out.print(curr.data + " ");
• // Move to the previous node
• curr = curr.prev;
• }
• // Print newline after traversal
• System.out.println();
• }
• public static void main(String[] args) {
• // Sample usage of the doubly linked
• // list and traversal functions
• Node head = new Node(1);
• Node second = new Node(2);
• Node third = new Node(3);
• head.next = second;
• second.prev = head;
• second.next = third;
• third.prev = second;
• System.out.println("Forward Traversal:");
• forwardTraversal(head);
• System.out.println("Backward Traversal:");
• backwardTraversal(third);
• }
• }
• Finding Length of Doubly Linked List
• To find the length of doubly list, we can use the
following steps:
• Start at the head of the list.
• Traverse through the list, counting each node visited.
• Return the total count of nodes as the length of the
list.
• class GfG {
• // Function to find the length of
• // a doubly linked list
• static int FindLength(Node head) {
• int count = 0;
• for (Node cur = head; cur != null; cur = cur.next)
• count++;
• return count;
• }
• Insertion at the Beginning in Doubly Linked List
• To insert a new node at the beginning of the doubly list, we can
use the following steps:
• Create a new node, say new_node with the given data and set its
previous pointer to null, new_node->prev = NULL.
• Set the next pointer of new_node to current head, new_node-
>next = head.
• If the linked list is not empty, update the previous pointer of the
current head to new_node, head->prev = new_node.
• Return new_node as the head of the updated linked list.
class GfG {
static Node insertBegin(Node head, int data) {
Node new_node = new Node(data);
new_node.next = head;
if (head != null) {
head.prev = new_node;
}
return new_node;
}
• // Print the doubly linked list
• static void printList(Node head) {
• Node curr = head;
• while (curr != null) {
• System.out.print(curr.data + " ");
• curr = curr.next;
• }
• System.out.println();
• }
• public static void main(String[] args) {
• Node head = new Node(2);
• head.next = new Node(3);
• head.next.prev = head;
• head.next.next = new Node(4);
• head.next.next.prev = head.next;
• System.out.print("Original Linked List: ");
• printList(head);
• head = insertBegin(head, 1);
• System.out.print(
• "After inserting Node 1 at the front: ");
• printList(head);
• }
• }
• public static void main(String[] args) {
• Node head = new Node(2);
• head.next = new Node(3);
• head.next.prev = head;
• head.next.next = new Node(4);
• head.next.next.prev = head.next;
• System.out.print("Original Linked List: ");
• printList(head);
• head = insertBegin(head, 1);
• System.out.print(
• "After inserting Node 1 at the front: ");
• printList(head);}}
• Insertion at the End of Doubly Linked List
• To insert a new node at the end of the doubly linked list, we can use the
following steps:
• Allocate memory for a new node and assign the provided value to its data
field.
• Initialize the next pointer of the new node to nullptr.
• If the list is empty:
– Set the previous pointer of the new node to nullptr.
– Update the head pointer to point to the new node.
• If the list is not empty:
– Traverse the list starting from the head to reach the last node.
– Set the next pointer of the last node to point to the new node.
– Set the previous pointer of the new node to point to the last node.
// Java Program to insert a node at the end of
// doubly linked list
class Node {
int data;
Node next, prev;
Node(int newData) {
data = newData;
next = prev = null;
}
}
class GFG {
public static Node insertEnd(Node head, int newData) {
Node newNode = new Node(newData);
if (head == null) {
head = newNode;
}
else {
Node curr = head;
while (curr.next != null) {
curr = curr.next;
}
curr.next = newNode;
newNode.prev = curr;
}
return head;
}
• public static void printList(Node head) {
• Node curr = head;
• while (curr != null) {
• System.out.print(curr.data + " ");
• curr = curr.next;
• }
• System.out.println();
• }


public static void main(String[] args) {
Node head = new Node(1);
head.next = new Node(2);
head.next.prev = head;
head.next.next = new Node(3);
head.next.next.prev = head.next;
System.out.println("Original Linked List: ");
printList(head);
System.out.println(
"Inserting Node with data 4 at the end: ");
int data = 4;
head = insertEnd(head, data);
printList(head);
}
}
• Insertion at a Specific Position in Doubly Linked List
• To insert a node at a specific Position in doubly linked
list, we can use the following steps:

• To insert a new node at a specific position,
• If position = 1, create a new node and make it the head of the linked list
and return it.
• Otherwise, traverse the list to reach the node at position – 1, say curr.
• If the position is valid, create a new node with given data, say new_node.
• Update the next pointer of new node to the next of current node and prev
pointer of new node to current node, new_node->next = curr-
>next and new_node->prev = curr.
• Similarly, update next pointer of current node to the new node, curr->next
= new_node.
• If the new node is not the last node, update prev pointer of new node’s
next to the new node, new_node->next->prev = new_node.
• Be
• class GFG {
• public static Node insertAtPosition(Node head, int pos, int new_data) {
• Node new_node = new Node(new_data);
• if (pos == 1) {
• new_node.next = head;
• if (head != null) {
• head.prev = new_node;
• }

• // Set the new node as the head of linked list


• head = new_node;
• return head;
• }

• Node curr = head;



• // Traverse the list to find the node before
• //the insertion point
• for (int i = 1; i < pos - 1 && curr != null; ++i) {
• curr = curr.next;
• }

• // If the position is out of bounds


• if (curr == null) {
• System.out.println("Position is out of bounds.");
• return head;
• }

• // Set the prev of new node to curr


• new_node.prev = curr;

• // Set the next of new node to next of curr


• new_node.next = curr.next;

• // Update the next of current node to new node


• curr.next = new_node;

• // If the new node is not the last node, update


• //prev of next node to new node
• if (new_node.next != null) {
• new_node.next.prev = new_node;
• }

• // Return the head of the doubly linked list


• return head;
• }

• // Function to print the linked list


• public static void printList(Node head) {
• Node curr = head;
• while (curr != null) {
• System.out.print(curr.data + " ");
• curr = curr.next;
• }
• System.out.println();
• }
• public static void main(String[] args) {
• // Create a hardcoded doubly linked list:
• // 1 <-> 2 <-> 4
• Node head = new Node(1);
• head.next = new Node(2);
• head.next.prev = head;
• head.next.next = new Node(4);
• head.next.next.prev = head.next;
• // Print the original list
• System.out.print("Original Linked List: ");
• printList(head);

• // Insert new node with data 3 at position 3
• System.out.print("Inserting Node with data 3 at position 3: ");
• int data = 3;
• int pos = 3;
• head = insertAtPosition(head, pos, data);

• // Print the updated list


• printList(head);
• }
• }
• Deletion at the Beginning in Doubly Linked List
• To delete a node at the beginning in doubly linked list, we can
use the following steps:
• Check if the list is empty, there is nothing to delete, return.
• Store the head pointer in a variable, say temp.
• Update the head of linked list to the node next to the current
head, head = head->next.
• If the new head is not NULL, update the previous pointer of
new head to NULL, head->prev = NULL.
• // Java Program to delete a node from the
• // beginning of Doubly Linked List
• class Node {
• int data;
• Node next;
• Node prev;
• Node(int x) {
• data = x;
• next = null;
• prev = null;
• }
• }
• class GfG {
• static Node delHead(Node head) {
• if (head == null) {
• return null;
• }
• Node temp = head;
• head = head.next;
• if (head != null) {
• head.prev = null;
• }
• return head;
• }
• static void printList(Node head) {
• Node curr = head;
• while (curr != null) {
• System.out.print(curr.data + " ");
• curr = curr.next;
• }
• System.out.println();
• }
• public static void main(String[] args) {
• Node head = new Node(1);
• head.next = new Node(2);
• head.next.prev = head;
• head.next.next = new Node(3);
• head.next.next.prev = head.next;

• head = delHead(head);
• printList(head);
• }
• }
• public static void main(String[] args) {
• Node head = new Node(1);
• head.next = new Node(2);
• head.next.prev = head;
• head.next.next = new Node(3);
• head.next.next.prev = head.next;
• head = delHead(head);
• printList(head);
• }
• }
• Deletion at the End in Doubly Linked List
• To delete a node at the end in doubly linked list, we can use
the following steps:
• Check if the doubly linked list is empty. If it is empty, then
there is nothing to delete.
• If the list is not empty, then move to the last node of the
doubly linked list, say curr.
• Update the second-to-last node’s next pointer to NULL, curr-
>prev->next = NULL.
• Free the memory allocated for the node that was deleted
• // Java Program to delete a node from the
• // end of Doubly Linked List
• class Node {
• int data;
• Node prev;
• Node next;
• Node(int d) {
• data = d;
• prev = null;
• next = null;
• }
• }
public class GfG {
• static Node delLast(Node head) {
• if (head == null) {
• return null;
• }
• if (head.next == null) {
• return null;
• }
• // Traverse to the last node
• Node curr = head;
• while (curr.next != null) {
• curr = curr.next;
• }

• // Update the previous node's next pointer


• if (curr.prev != null) {
• curr.prev.next = null;
• }

• // Return the updated head


• return head;
• }

• static void printList(Node head) {


• Node curr = head;
• while (curr != null) {
• System.out.print(curr.data + " ");
• curr = curr.next;
• }
• System.out.println();
• }

• public static void main(String[] args) {



• // Create a hardcoded doubly linked list:
• // 1 <-> 2 <-> 3
• Node head = new Node(1);
• head.next = new Node(2);
• head.next.prev = head;
• head.next.next = new Node(3);
• head.next.next.prev = head.next;

• head = delLast(head);

• printList(head);
• }
• }
• public static void main(String[] args) {
• // Create a hardcoded doubly linked list:
• // 1 <-> 2 <-> 3
• Node head = new Node(1);
• head.next = new Node(2);
• head.next.prev = head;
• head.next.next = new Node(3);
• head.next.next.prev = head.next;
• head = delLast(head);
• printList(head);
• }
• }
• Deletion at a specific position in Doubly Linked List
• To delete a node before a specific node in a doubly linked list, we can use the
following steps:
• Initialize a variable , say curr points to the node with the key value in the linked list.
• if found , check if curr->prev is not NULL.
– If it’s NULL, the node to be deleted is the head node, so there is no node to
delete before it.
– else , set a pointer nodeDelete to curr->prev, which is the node to be deleted.
– Update curr->prev to point to nodeDelete ->prev.
– If nodeDelete ->prev is not NULL, update nodeDelete->prev->next point
to curr.
• Delete nodeDelete to free memory.
• // Java Program to delete a node before a given node of
• // doubly linked list

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

• Node(int x) {
• data = x;
• next = null;
• prev = null;
• }
• }
• class GfG {
• // Function to delete a node before a given node in a
• // doubly linked list
• static Node deleteBefore(Node head, int key) {
• Node curr = head;

• // Find the node with the given key


• while (curr != null) {
• if (curr.data == key)
• break;
• curr = curr.next;
• }

• // If curr is null or curr.prev is null, there is no


• // node to delete
• if (curr == null || curr.prev == null)
• return head;

• // Node to be deleted
• Node nodeToDelete = curr.prev;

• // Update the prev of the current node to the prev


• // of the node to be deleted
• curr.prev = nodeToDelete.prev;

• // If nodeToDelete's prev is not null, update its


• // next pointer to the current node
• if (nodeToDelete.prev != null) {
• nodeToDelete.prev.next = curr;
• }
• else {

• // If nodeToDelete is the head node
• head = curr;
• }

• return head;
• }

• static void printList(Node head) {


• Node curr = head;
• while (curr != null) {
• System.out.print(curr.data + " ");
• curr = curr.next;
• }
• System.out.println();
• }

• public static void main(String[] args) {



• // Create a hardcoded doubly linked list:
• // 1 <-> 2 <-> 3 <-> 4
• Node head = new Node(1);
• head.next = new Node(2);
• head.next.prev = head;
• head.next.next = new Node(3);
• head.next.next.prev = head.next;
• head.next.next.next = new Node(4);
• head.next.next.next.prev = head.next.next;

• head = deleteBefore(head, 3);


• printList(head);
• }
• }
public static void main(String[] args) {
Node head = new Node(1);
head.next = new Node(2);
head.next.prev = head;
head.next.next = new Node(3);
head.next.next.prev = head.next;
head.next.next.next = new Node(4);
head.next.next.next.prev = head.next.next;
head = deleteBefore(head, 3);
printList(head);
}
}
• A circular linked list is a special type of linked list where all the nodes are
connected to form a circle.
• Circular Singly Linked List
• In Circular Singly Linked List, each node has just one pointer called the “next”
pointer. The next pointer of last node points back to the first node and this results
in forming a circle. In this type of Linked list we can only move through the list in
one direction.

• 2. Circular Doubly Linked List:


• In circular doubly linked list, each node has two pointers prev and next, similar to
doubly linked list. The prev pointer points to the previous node and the next points
to the next node. Here, in addition to the last node storing the address of the first
node, the first node will also store the address of the last node.

• class Node {
• int data;
• Node next;
• Node(int data)
• {
• this.data = data;
• this.next = null;
• }
• }
• https://www.geeksforgeeks.org/circular-linked-list-java/

You might also like