[go: up one dir, main page]

Open In App

Detect loop or cycle in a linked list

Last Updated : 09 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a singly linked list, check if the linked list has a loop (cycle) or not. A loop means that the last node of the linked list is connected back to a node in the same list.

Examples:

Input: head: 1 -> 3 -> 4 -> NULL 
Output: true

Input: head: 1 -> 8 -> 3 -> 4 -> NULL 
Output: false

[Naive Approach] Using HashSet – O(n) Time and O(n) Space:

The idea is to insert the nodes in the Hashset while traversing and whenever a node is encountered that is already present in the hashset then return true.

Follow the steps below to solve the problem:

  • Initialize an empty HashSet to store the addresses (or references) of the visited nodes.
  • Start traversing the linked list from head and for every node check if its address (or reference) is already in the HashSet
    • If the node is NULL, represents the end of Linked List , return false as there is no loop.
    • If the node’s address is not in the HashSet, add it to the HashSet.
    • If the node’s address is already in the HashSet, which indicates there’s a cycle (loop) in the list. In this case, return true.

Below is the implementation of the above approach:

C++
// C++ program to detect loop in a linked list
// using hashset
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node* next;
    Node(int x) {
        this->data = x;
        this->next = nullptr;
    }
};

// Function that returns true if there is a loop in linked
// list else returns false.
bool detectLoop(Node* head) {
    unordered_set<Node*>st;

    // loop that runs till the head is nullptr
    while (head != nullptr) {

        // If this node is already present
        // in hashmap it means there is a cycle
        // (Because you will be encountering the
        // node for the second time).
        if (st.find(head) != st.end())
            return true;

        // If we are seeing the node for
        // the first time, insert it in hash
        st.insert(head);

        head = head->next;
    }
    return false;
}

int main() {

    // Create a hard-coded linked list:
    // 10 -> 20 -> 30 -> 40 -> 50 -> 60
    Node* head = new Node(10);
    head->next = new Node(20);
    head->next->next = new Node(30);
    head->next->next->next = new Node(40);
    head->next->next->next->next = new Node(50);
    head->next->next->next->next->next = new Node(60);
    
    head->next->next->next->next = head;

    if (detectLoop(head))
        cout << "true";
    else
        cout << "false";

    return 0;
}
Java
// Java program to detect loop in a linked list
// using hashset
import java.util.HashSet;
import java.util.Set;

class Node {
    int data;
    Node next;

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

class GfG {

    // Function that returns true if there is a loop in
    // linked list else returns false.
    static boolean detectLoop(Node head) {
        Set<Node> st = new HashSet<>();

        // loop that runs till the head is null
        while (head != null) {

            // If this node is already present
            // in hashmap it means there is a cycle
            // (Because you will be encountering the
            // node for the second time).
            if (st.contains(head))
                return true;

            // If we are seeing the node for
            // the first time, insert it in hash
            st.add(head);

            head = head.next;
        }
        return false;
    }

    public static void main(String[] args) {

        // Create a hard-coded linked list:
        // 10 -> 20 -> 30 -> 40 -> 50 -> 60
        Node head = new Node(10);
        head.next = new Node(20);
        head.next.next = new Node(30);
        head.next.next.next = new Node(40);
        head.next.next.next.next = new Node(50);
        head.next.next.next.next.next = new Node(60);
      
        head.next.next.next.next = head;

        if (detectLoop(head))
            System.out.println("true");
        else
            System.out.println("false");
    }
}
Python
# Python program to detect loop
# in the linked list using hashset

class Node:
    def __init__(self, x):
        self.data = x
        self.next = None

# Function that returns true if there is a loop in linked
# list else returns false.
def detect_loop(head):
    st = set()

    # loop that runs till the head is None
    while head is not None:

        # If this node is already present
        # in hashmap it means there is a cycle
        # (Because you will be encountering the
        # node for the second time).
        if head in st:
            return True

        # If we are seeing the node for
        # the first time, insert it in hash
        st.add(head)

        head = head.next
    return False

# Create a hard-coded linked list:
# 10 -> 20 -> 30 -> 40 -> 50 -> 60 -> 70
head = Node(10)
head.next = Node(20)
head.next.next = Node(30)
head.next.next.next = Node(40)
head.next.next.next.next = Node(50)
head.next.next.next.next.next = Node(60)

head.next.next.next.next = head

if detect_loop(head):
    print("true")
else:
    print("false")
C#
// C# program to detect loop in a linked list
// using hashset
using System;
using System.Collections.Generic;

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

class GfG {

    // Function that returns true if there is a loop in
    // linked list else returns false.
    public static bool detectLoop(Node head) {
        HashSet<Node> st = new HashSet<Node>();

        // loop that runs till the head is null
        while (head != null) {

            // If this node is already present
            // in hashmap it means there is a cycle
            // (Because you will be encountering the
            // node for the second time).
            if (st.Contains(head))
                return true;

            // If we are seeing the node for
            // the first time, insert it in hash
            st.Add(head);

            head = head.next;
        }
        return false;
    }

    static void Main() {

        // Create a hard-coded linked list:
        // 10 -> 20 -> 30 -> 40 -> 50 -> 60 -> 70
        Node head = new Node(10);
        head.next = new Node(20);
        head.next.next = new Node(30);
        head.next.next.next = new Node(40);
        head.next.next.next.next = new Node(50);
        head.next.next.next.next.next = new Node(60);

        head.next.next.next.next = head;

        if (detectLoop(head))
            Console.WriteLine("true");
        else
            Console.WriteLine("false");
    }
}
JavaScript
// JavaScript program to detect loop in a linked list
// using hashset
class Node {
    constructor(x) {
        this.data = x;
        this.next = null;
    }
}

// Function that returns true if there is a loop in
// linked list else returns false.
function detectLoop(head) {
    let st = new Set();

    // loop that runs till the head is null
    while (head !== null) {

        // If this node is already present
        // in hashmap it means there is a cycle
        // (Because you will be encountering the
        // node for the second time).
        if (st.has(head))
            return true;

        // If we are seeing the node for
        // the first time, insert it in hash
        st.add(head);

        head = head.next;
    }
    return false;
}

// Create a hard-coded linked list:
// 10 -> 20 -> 30 -> 40 -> 50 -> 60 -> 70
let head = new Node(10);
head.next = new Node(20);
head.next.next = new Node(30);
head.next.next.next = new Node(40);
head.next.next.next.next = new Node(50);
head.next.next.next.next.next = new Node(60);

head.next.next.next.next = head;

if (detectLoop(head))
    console.log("true");
else
    console.log("false");

Output
true

Time complexity: O(n), where n is the number of nodes in the Linked List.
Auxiliary Space: O(n), n is the space required to store the value in the hash set.

[Expected Approach] Using Floyd’s Cycle-Finding Algorithm – O(n) Time and O(1) Space:

This idea is to use Floyd’s Cycle-Finding Algorithm to find a loop in a linked list. It uses two pointers slow and fast, fast pointer move two steps ahead and slow will move one step ahead at a time.

Follow the steps below to solve the problem:

  • Traverse linked list using two pointers.
  • Move one pointer(slow) by one step ahead and another pointer(fast) by two steps ahead.
  • If these pointers meet at the same node then there is a loop. If pointers do not meet then the linked list doesn’t have a loop.

Below is the illustration of above algorithm:


For more details about the working & proof of this algorithm, Please refer to this article, How does Floyd’s Algorithm works.

C++
// C++ program to detect loop in a linked list
// using Floyd's Cycle-Finding Algorithm
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node* next;
    Node(int x) {
        this->data = x;
        this->next = nullptr;
    }
};

// Function that returns true if there is a loop in linked
// list else returns false.
int detectLoop(Node* head) {
  
    // Fast and slow pointers initially points to the head
    Node *slow = head, *fast = head;

    // Loop that runs while fast and slow pointer are not
    // nullptr and not equal
    while (slow && fast && fast->next) {
        slow = slow->next;
        fast = fast->next->next;

        // If fast and slow pointer points to the same node,
        // then the cycle is detected
        if (slow == fast) {
            return 1;
        }
    }
    return 0;
}

int main() {

    // Create a hard-coded linked list:
    // 10 -> 20 -> 30 -> 40 -> 50 -> 60
    Node* head = new Node(10);
    head->next = new Node(20);
    head->next->next = new Node(30);
    head->next->next->next = new Node(40);
    head->next->next->next->next = new Node(50);
    head->next->next->next->next->next = new Node(60);

    head->next->next->next->next = head;

    if (detectLoop(head))
        cout << "true";
    else
        cout << "false";

    return 0;
}
C
// C program to detect loop in a linked list
// using Floyd's Cycle-Finding Algorithm
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

// A linked list node
struct Node {
    int data;
    struct Node* next;
};


// Function that returns true if there is a loop in linked
// list else returns false.
int detectLoop(struct Node* head) {
  
    // Fast and slow pointers initially points to the head
    struct Node *slow = head, *fast = head;

    // Loop that runs while fast and slow pointer are not
    // nullptr and not equal
    while (slow && fast && fast->next) {
        slow = slow->next;
        fast = fast->next->next;

        // If fast and slow pointer points to the same node,
        // then the cycle is detected
        if (slow == fast) {
            return 1;
        }
    }
    return 0;
}

struct Node* createNode(int new_data) {
    struct Node* new_node
        = (struct Node*)malloc(sizeof(struct Node));
    new_node->data = new_data;
    new_node->next = NULL;
    return new_node;
}
int main() {

    // Create a hard-coded linked list:
    // 10 -> 20 -> 30 -> 40 -> 50 -> 60
    struct Node* head = createNode(10);
    head->next = createNode(20);
    head->next->next = createNode(30);
    head->next->next->next = createNode(40);
    head->next->next->next->next = createNode(50);
    head->next->next->next->next->next = createNode(60);

    head->next->next->next->next = head;

    if (detectLoop(head))
        printf("true");
    else
        printf("false");

    return 0;
}
Java
// Java program to detect loop in a linked list
// using Floyd's Cycle-Finding Algorithm
import java.util.*;

class Node {
    int data;
    Node next;

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

class GfG {

    // Function that returns true if there is a loop in
    // linked list else returns false.
    static boolean detectLoop(Node head) {
      
        // Fast and slow pointers initially points to the
        // head
        Node slow = head, fast = head;

        // Loop that runs while fast and slow pointer are
        // not null and not equal
        while (slow != null && fast != null
               && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;

            // If fast and slow pointer points to the same
            // node, then the cycle is detected
            if (slow == fast) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {

        // Create a hard-coded linked list:
        // 10 -> 20 -> 30 -> 40 -> 50 -> 60
        Node head = new Node(10);
        head.next = new Node(20);
        head.next.next = new Node(30);
        head.next.next.next = new Node(40);
        head.next.next.next.next = new Node(50);
        head.next.next.next.next.next = new Node(60);

        head.next.next.next.next = head;


        if (detectLoop(head))
            System.out.println("true");
        else
            System.out.println("false");
    }
}
Python
# C++ program to detect loop in a linked list
# using Floyd's Cycle-Finding Algorithm
class Node:
    def __init__(self, new_data):
        self.data = new_data
        self.next = None

# Function that returns true if there is a loop in linked
# list else returns false.
def detect_loop(head):

    # Fast and slow pointers initially points to the head
    slow = head
    fast = head

    # Loop that runs while fast and slow pointer are not
    # None and not equal
    while slow and fast and fast.next:
        slow = slow.next
        fast = fast.next.next

        # If fast and slow pointer points to the same node,
        # then the cycle is detected
        if slow == fast:
            return True
    return False


# Create a hard-coded linked list:
# 10 -> 20 -> 30 -> 40 -> 50 -> 60
head = Node(10)
head.next = Node(20)
head.next.next = Node(30)
head.next.next.next = Node(40)
head.next.next.next.next = Node(50)
head.next.next.next.next.next = Node(60)

head.next.next.next.next = head

if detect_loop(head):
    print("true")
else:
    print("false")
C#
// C# program to detect loop in a linked list
// using Floyd's Cycle-Finding Algorithm
using System;

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

class GfG {

    // Function that returns true if there is a loop in linked
    // list else returns false.
    static bool detectLoop(Node head) {
      
        // Fast and slow pointers initially points to the head
        Node slow = head, fast = head;

        // Loop that runs while fast and slow pointer are not
        // null and not equal
        while (slow != null && fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;

            // If fast and slow pointer points to the same node,
            // then the cycle is detected
            if (slow == fast) {
                return true;
            }
        }
        return false;
    }

    static void Main() {

        // Create a hard-coded linked list:
        // 10 -> 20 -> 30 -> 40 -> 50 -> 60
        Node head = new Node(10);
        head.next = new Node(20);
        head.next.next = new Node(30);
        head.next.next.next = new Node(40);
        head.next.next.next.next = new Node(50);
        head.next.next.next.next.next = new Node(60);


        head.next.next.next.next = head;

        if (detectLoop(head))
            Console.WriteLine("true");
        else
            Console.WriteLine("false");
    }
}
JavaScript
// Javascript program to detect loop in a linked list
// using Floyd's Cycle-Finding Algorithm
class Node {
    constructor(x) {
        this.data = x;
        this.next = null;
    }
}

// Function that returns true if there is a loop in
// linked list else returns false.
function detectLoop(head) {

    // Fast and slow pointers initially points to the
    // head
    let slow = head, fast = head;

    // Loop that runs while fast and slow pointer are
    // not null and not equal
    while (slow !== null && fast !== null
           && fast.next !== null) {
        slow = slow.next;
        fast = fast.next.next;

        // If fast and slow pointer points to the same
        // node, then the cycle is detected
        if (slow === fast) {
            return true;
        }
    }
    return false;
}

// Create a hard-coded linked list:
// 10 -> 20 -> 30 -> 40 -> 50 -> 60
let head = new Node(10);
head.next = new Node(20);
head.next.next = new Node(30);
head.next.next.next = new Node(40);
head.next.next.next.next = new Node(50);
head.next.next.next.next.next = new Node(60);


head.next.next.next.next = head;

if (detectLoop(head))
    console.log("true");
else
    console.log("false");

Output
true

Time complexity: O(n), where n is the number of nodes in the Linked List.
Auxiliary Space: O(1). 

Related Article:



Previous Article
Next Article

Similar Reads

Detect Cycle in a Linked List using Map
Given a Linked List, check if the linked list has a loop or not.There are various methods shown here: Detect Cycle in Linked List Example Input: 20->4->54->6->NULL Output: No loop is detected. Explanation: While traversing the linked list, we reach the end of the linked list. Therefore, no loop is present in the linked list. Input: 20-
7 min read
Detect and Remove Loop in Linked List
Given the head of a linked list that may contain a loop. A loop means that the last node of the linked list is connected back to a node in the same list. The task is to Remove the loop from the linked list (if it exists). Example: Input: Output: 1 -> 3 -> 4 Explanation: The Loop is removed from the above example. Input: Output: 1 -> 8 -
14 min read
Find length of loop/cycle in given Linked List
Given the head of a linked list. The task is to find the length of the loop in the linked list. If the loop is not present return 0. Examples: Input: head: 25 -> 14 -> 19 -> 33 -> 10 -> 21 -> 39 ->90 ->58 -> 45 -> 33Output: 7Explanation: The loop is present in the below-linked list and the length of the loop is 7. Inpu
12 min read
Detect a negative cycle in a Graph | (Bellman Ford)
Given a directed weighted graph, the task is to find whether the given graph contains any negative-weight cycle or not. Note: A negative-weight cycle is a cycle in a graph whose edges sum to a negative value. Example: Input: Output: No Input: Output: Yes Algorithm to Find Negative Cycle in a Directed Weighted Graph Using Bellman-Ford:Initialize dis
15+ min read
Detect cycle in the graph using degrees of nodes of graph
Given a graph, the task is to detect a cycle in the graph using degrees of the nodes in the graph and print all the nodes that are involved in any of the cycles. If there is no cycle in the graph then print -1. Examples: Input: Output: 0 1 2 Approach: Recursively remove all vertices of degree 1. This can be done efficiently by storing a map of vert
11 min read
Detect cycle in Directed Graph using Topological Sort
Given a Directed Graph consisting of N vertices and M edges and a set of Edges[][], the task is to check whether the graph contains a cycle or not using Topological sort. Topological sort of directed graph is a linear ordering of its vertices such that, for every directed edge U -> V from vertex U to vertex V, U comes before V in the ordering. E
9 min read
Detect Cycle in a 2D grid
Given a 2D grid arr[][] with different characters, the task is to detect whether it contains a cycle or not. A sequence of characters or integers c1, c2, .... cM is called a cycle if and only if it meets the following condition: M should at least be 4.All characters belong to the same character or integer. For all 0 <= i <= M -1 : ci and ci +
15 min read
Detect a negative cycle in a Graph using Shortest Path Faster Algorithm
Given a graph G consisting of nodes valued [0, N - 1], a source S, and an array Edges[][3] of type {u, v, w} that denotes that there is a directed edge between node u and v with weight w, the task is to check if there exists a negative cycle from the given source. If found to be true, then print "Yes". Otherwise, print "No". A negative cycle is a c
11 min read
Detect Cycle in a Directed Graph using BFS
Given a directed graph, check whether the graph contains a cycle or not. Your function should return true if the given graph contains at least one cycle, else return false. For example, the following graph contains two cycles 0->1->2->3->0 and 2->4->2, so your function must return true. Recommended: Please solve it on "PRACTICE" f
11 min read
Detect Cycle in Graph using DSU
Given an undirected graph, the task is to check if the graph contains a cycle or not, using DSU. Examples: Input: The following is the graph Output: YesExplanation: There is a cycle of vertices {0, 1, 2}. Recommended PracticeDetect Cycle using DSUTry It!We already have discussed an algorithm to detect cycle in directed graph. Here Union-Find Algori
13 min read
Detect Cycle in a directed graph using colors
Given a directed graph, check whether the graph contains a cycle or not. Your function should return true if the given graph contains at least one cycle, else return false. Example: Input: n = 4, e = 6 0 -> 1, 0 -> 2, 1 -> 2, 2 -> 0, 2 -> 3, 3 -> 3 Output: Yes Explanation: This diagram clearly shows a cycle 0 -> 2 -> 0. Inpu
11 min read
Detect cycle in an undirected graph using BFS
Given an undirected graph, how to check if there is a cycle in the graph? For example, the following graph has a cycle of 1-0-2-1.  Recommended: Please solve it on "PRACTICE" first, before moving on to the solution.We have discussed cycle detection for the directed graph. We have also discussed a union-find algorithm for cycle detection in undirect
5 min read
Detect Cycle in a Directed Graph
Given the root of a Directed graph , The task is to check whether the graph contains a cycle or not. Examples: Input: V = 4, E = 6 Output: Yes Explanation: The diagram clearly shows a cycle 0 -> 2 -> 0 Input: V = 4, E = 4 Output: No Explanation: The diagram clearly shows no cycle. Detect Cycle in a Directed Graph using DFS:The problem can be
14 min read
Detect cycle in an undirected graph
Given an undirected graph, The task is to check if there is a cycle in the given graph. Examples: Input: V = 4, E = 4 Output: Yes Explanation: The diagram clearly shows a cycle 0 to 2 to 1 to 0 Input: V = 4, E = 3 Output: No Explanation: There is no cycle in the given graph. Find cycle in Undirected Graph using BFS:When we do BFS traversal, we main
9 min read
Time taken by Loop unrolling vs Normal loop
We have discussed loop unrolling. The idea is to increase performance by grouping loop statements so that there are less number of loop control instruction and loop test instructions C/C++ Code // CPP program to compare normal loops and // loops with unrolling technique #include <iostream> #include <time.h> using namespace std; int main
6 min read
Time Complexity of a Loop when Loop variable “Expands or Shrinks” exponentially
For such cases, time complexity of the loop is O(log(log(n))).The following cases analyse different aspects of the problem. Case 1 : for (int i = 2; i <=n; i = pow(i, k)) { // some O(1) expressions or statements } In this case, i takes values 2, 2k, (2k)k = 2k2, (2k2)k = 2k3, ..., 2klogk(log(n)). The last term must be less than or equal to n, an
1 min read
Make a loop at k-th position in a linked list
Given a linked list and a position k. Make a loop at k-th position Examples: Input : Given linked list Output : Modified linked list Algorithm: Traverse the first linked list till k-th point Make backup of the k-th node Traverse the linked list till end Attach the last node with k-th node Implementation: C/C++ Code // CPP program for making loop at
8 min read
Make all even values inside loop equal in given Linked list
Given a linked list that contains integers, your task is to find the minimum cost for making all even numbers that are inside the cycle equal. You can perform the below-mentioned operations to achieve this : Increase a node's value by 1, this will cost 1 operation.Decrease a node's value by 1, this will cost 1 operation.Examples : Input: 1->2-
11 min read
Check linked list with a loop is palindrome or not
Given a linked list with a loop, the task is to find whether it is palindrome or not. You are not allowed to remove the loop. Examples: Input : 1 -> 2 -> 3 -> 2 /|\ \|/ ------- 1 Output: Palindrome Linked list is 1 2 3 2 1 which is a palindrome. Input : 1 -> 2 -> 3 -> 4 /|\ \|/ ------- 1 Output: Not Palindrome Linked list is 1 2 3
14 min read
Javascript Program For Checking Linked List With A Loop Is Palindrome Or Not
Given a linked list with a loop, the task is to find whether it is palindrome or not. You are not allowed to remove the loop. Examples: Input: 1 -> 2 -> 3 -> 2 /| |/ ------- 1 Output: PalindromeLinked list is 1 2 3 2 1 which is a palindrome.Input: 1 -> 2 -> 3 -> 4 /| |/ ------- 1 Output: Not PalindromeLinked list is 1 2 3 4 1 whic
4 min read
Javascript Program For Finding The Length Of Loop In Linked List
Write a function detectAndCountLoop() that checks whether a given Linked List contains loop and if loop is present then returns count of nodes in loop. For example, the loop is present in below-linked list and length of the loop is 4. If the loop is not present, then the function should return 0. Approach: It is known that Floyd’s Cycle detection a
3 min read
Find first node of loop in a linked list
Given the head of a linked list that may contain a loop. A loop means that the last node of the linked list is connected back to a node in the same list. The task is to find the Starting node of the loop in the linked list if there is no loop in the linked list return -1. Example : Input: Output: 3Explanation: We can see that there exists a loop in
14 min read
Convert Singly Linked List to XOR Linked List
Prerequisite: XOR Linked List – A Memory Efficient Doubly Linked List | Set 1XOR Linked List – A Memory Efficient Doubly Linked List | Set 2 An XOR linked list is a memory efficient doubly linked list in which the next pointer of every node stores the XOR of previous and next node's address. Given a singly linked list, the task is to convert the gi
9 min read
XOR linked list- Remove first node of the linked list
Given an XOR linked list, the task is to remove the first node of the XOR linked list. Examples: Input: XLL = 4 < – > 7 < – > 9 < – > 7 Output: 7 < – > 9 < – > 7 Explanation: Removing the first node of the XOR linked list modifies XLL to 7 < – > 9 < – > 7 Input: XLL = NULL Output: List Is Empty Approach: Th
11 min read
Remove all occurrences of one Linked list in another Linked list
Given two linked lists head1 and head2, the task is to remove all occurrences of head2 in head1 and return the head1. Examples: Input: head1 = 2 -> 3 -> 4 -> 5 -> 3 -> 4, head2 = 3 -> 4Output: 2 -> 5Explanation: After removing all occurrences of 3 -> 4 in head1 output is 2 -> 5. Input: head1 = 3 -> 6 -> 9 -> 8 -
9 min read
Count occurrences of one linked list in another Linked List
Given two linked lists head1 and head2, the task is to find occurrences of head2 in head1. Examples: Input: Head1 = 1->2->3->2->4->5->2->4, Head2 = 2->4Output: Occurrences of head2 in head1: 2 Input: Head1 = 3->4->1->5->2, Head2 = 3->4Output: Occurrences of Head2 in Head1: 1 Approach 1: To solve the problem us
15 min read
When is Doubly Linked List more Efficient than Singly Linked List?
Did you know there are some cases where a Doubly Linked List is more efficient than a Singly Linked List, even though it takes more memory compared to a Singly Linked List? What are those Cases? Well, we will discuss that in the following article, But first, let's talk about Singly and linked lists: What is a Singly Linked List?A singly linked list
4 min read
XOR Linked List - Reverse a Linked List in groups of given size
Given a XOR linked list and an integer K, the task is to reverse every K nodes in the given XOR linked list. Examples: Input: XLL = 7< – > 6 < – > 8 < – > 11 < – > 3, K = 3 Output: 8 < – > 6 < – > 7 < – > 3 < – > 11 Explanation: Reversing first K(= 3) nodes modifies the Linked List to 8 < – > 6
13 min read
XOR Linked List: Remove last node of the Linked List
Given an XOR linked list, the task is to delete the node at the end of the XOR Linked List. Examples: Input: 4<–>7<–>9<–>7Output: 4<–>7<–>9Explanation: Deleting a node from the end modifies the given XOR Linked List to 4<–>7<–>9 Input: 10Output: List is emptyExplanation: After deleting the only node present
15+ min read
Is two way linked list and doubly linked list same?
Yes, a two-way linked list and a doubly linked list are the same. Both terms refer to a type of linked list where each node contains a reference to the next node as well as the previous node in the sequence. The term “two-way” emphasizes the ability to move in both directions through the list, while “doubly” highlights that there are two links per
3 min read
three90RightbarBannerImg