The Wayback Machine - https://web.archive.org/web/20240920065913/https://www.geeksforgeeks.org/rotate-a-linked-list/
Open In App

Rotate a Linked List

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

Given a singly linked list and an integer k, the task is to rotate the linked list to the left by k places.

Examples:

Input: linked list = 10 -> 20 -> 30 -> 40 -> 50, k = 4
Output: 50 -> 10 -> 20 -> 30 -> 40

Rotate-a-Linked-List

Explanation: After rotating the linked list to the left by 4 places, the 5th node, i.e node 50 becomes the head of the linked list and next pointer of node 50 points to node 10.

Input: linked list = 10 -> 20 -> 30 -> 40, k = 6
Output: 30 -> 40 -> 10 -> 20 

Rotate-a-Linked-List-2

Explanation: After rotating the linked list to the left by 6 places (same as rotating by 2 places as (k % len) = (6 % 4 = 2)) , the 3rd node, i.e node 30 becomes the head of the linked list and next pointer of node 40 points to node 10.

[Naive Approach] Shifting head node to the end k times – O(n * k) Time and O(1) Space

To rotate a linked list to the left k places, we can repeatedly move the head node to the end of the linked list k times.

C++
// C++ program to rotate a linked list by
// changing moving first node to end k times

#include <iostream>
using namespace std;

class Node {
  public:
    int data;
    Node *next;
    Node(int new_data) {
        data = new_data;
        next = nullptr;
    }
};

// Function to rotate the linked list
// left by k nodes
Node *rotate(Node *head, int k) {
    if (k == 0 || head == nullptr)
        return head;

    // Rotate the list by k nodes
    for (int i = 0; i < k; ++i) {
        Node *curr = head;
        while (curr->next != nullptr)
            curr = curr->next;
        
        // Move the first node to the last
        curr->next = head;
        curr = curr->next;
        head = head->next;
        curr->next = nullptr;
    }
    return head;
}

void printList(Node *node) {
    while (node != nullptr) {
        cout << node->data << " ";
        node = node->next;
    }
    cout << endl;
}

int main() {

    // Create a hard-coded linked list:
    // 10 -> 20 -> 30 -> 40
    Node *head = new Node(10);
    head->next = new Node(20);
    head->next->next = new Node(30);
    head->next->next->next = new Node(40);
  
    head = rotate(head, 6);
    printList(head);

    return 0;
}
C
// C program to rotate a linked list
// by changing moving first node to end k times.

#include <stdio.h>
#include <stdlib.h>

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

// Function to create a new node
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;
}

// Function to rotate the linked list
// left by k nodes
struct Node* rotate(struct Node *head, int k) {
    if (k == 0 || head == NULL)
        return head;

    // Rotate the list by k nodes
    for (int i = 0; i < k; ++i) {
        struct Node *curr = head;
        while (curr->next != NULL)
            curr = curr->next;

        // Move the first node to the last
        curr->next = head;
        curr = curr->next;
        head = head->next;
        curr->next = NULL;
    }
    return head;
}

void printList(struct Node *node) {
    while (node != NULL) {
        printf("%d ", node->data);
        node = node->next;
    }
    printf("\n");
}

int main() {
  
    // Create a hard-coded linked list:
    // 10 -> 20 -> 30 -> 40
    struct Node *head = createNode(10);
    head->next = createNode(20);
    head->next->next = createNode(30);
    head->next->next->next = createNode(40);
  
    head = rotate(head, 6);
    printList(head);

    return 0;
}
Java
// Java program to rotate a linked list
// by changing moving first node to end k times.

class Node {
    int data;
    Node next;

    Node(int new_data) {
        data = new_data;
        next = null;
    }
}

class GfG {

    // Function to rotate the linked list
    // left by k nodes
    static Node rotate(Node head, int k) {
        if (k == 0 || head == null)
            return head;

        // Rotate the list by k nodes
        for (int i = 0; i < k; ++i) {
            Node curr = head;
            while (curr.next != null)
                curr = curr.next;

            // Move the first node to the last
            curr.next = head;
            curr = curr.next;
            head = head.next;
            curr.next = null;
        }
        return head;
    }

    static void printList(Node node) {
        while (node != null) {
            System.out.print(node.data + " ");
            node = node.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
          
        // Create a hard-coded linked list:
        // 10 -> 20 -> 30 -> 40
        Node head = new Node(10);
        head.next = new Node(20);
        head.next.next = new Node(30);
        head.next.next.next = new Node(40);

        head = rotate(head, 6);
        printList(head);
    }
}
Python
# Python program to rotate a linked list
# by changing moving first node to end k times.

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

# Function to rotate the linked list
# left by k nodes
def rotate(head, k):
    if k == 0 or head is None:
        return head

    # Rotate the list by k nodes
    for _ in range(k):
        curr = head
        while curr.next is not None:
            curr = curr.next
        
        # Move the first node to the last
        curr.next = head
        curr = curr.next
        head = head.next
        curr.next = None
    
    return head

def printList(node):
    while node is not None:
        print(node.data, end=" ")
        node = node.next
    print()

if __name__ == "__main__":
  
    # Create a hard-coded linked list:
    # 10 -> 20 -> 30 -> 40
    head = Node(10)
    head.next = Node(20)
    head.next.next = Node(30)
    head.next.next.next = Node(40)

    head = rotate(head, 6)
    printList(head)
C#
// C# program to rotate a linked list
// by changing moving first node to end k times

using System;

class Node {
    public int data;
    public Node next;
    
    public Node(int new_data) {
        data = new_data;
        next = null;
    }
}

// Function to rotate the linked list
// left by k nodes
class GfG {
    static Node Rotate(Node head, int k) {
        if (k == 0 || head == null)
            return head;

        // Rotate the list by k nodes
        for (int i = 0; i < k; ++i) {
            Node curr = head;
            while (curr.next != null)
                curr = curr.next;
            
            // Move the first node to the last
            curr.next = head;
            curr = curr.next;
            head = head.next;
            curr.next = null;
        }
        return head;
    }

    static void PrintList(Node node) {
        while (node != null) {
            Console.Write(node.data + " ");
            node = node.next;
        }
        Console.WriteLine();
    }

    static void Main() {
          
        // Create a hard-coded linked list:
        // 10 -> 20 -> 30 -> 40
        Node head = new Node(10);
        head.next = new Node(20);
        head.next.next = new Node(30);
        head.next.next.next = new Node(40);

        head = Rotate(head, 6);
        PrintList(head);
    }
}
JavaScript
// Javascript program to rotate a linked list
// by changing moving first node to end k times.

class Node {
    constructor(new_data) {
        this.data = new_data;
        this.next = null;
    }
}

// Function to rotate the linked list
// left by k nodes
function rotate(head, k) {
    if (k === 0 || head === null) {
        return head;
    }

    // Rotate the list by k nodes
    for (let i = 0; i < k; ++i) {
        let curr = head;
        while (curr.next !== null) {
            curr = curr.next;
        }

        // Move the first node to the last
        curr.next = head;
        curr = curr.next;
        head = head.next;
        curr.next = null;
    }
    return head;
}

function printList(node) {
    let result = '';
    while (node !== null) {
        result += node.data + ' ';
        node = node.next;
    }
    console.log(result.trim());
}

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

head = rotate(head, 6);
printList(head);

Output
30 40 10 20 

Time Complexity: O(n * k), where n is the number of nodes in Linked List and k is the number of rotations.
Auxiliary Space: O(1)

[Expected Approach] By changing pointer of kth node – O(n) Time and O(1) Space

The idea is to first convert the linked list to circular linked list by updating the next pointer of last node to the head of linked list. Then, traverse to the kth node and update the head of the linked list to the (k+1)th node. Finally, break the loop by updating the next pointer of kth node to NULL.

How to handle large values of k?

For a linked list of size n, if we rotate the linked list to the left by n places, then the linked list will remain unchanged and if we rotate the list to the left by (n + 1) places, then it is same as rotating the linked list to the left by 1 place. Similarly, if we rotate the linked list k (k >= n) places to the left, then it is same as rotating the linked list by (k % n) places. So, we can simply update k with k % n to handle large values of k.

Working:


Below is the implementation of the above algorithm:

C++
// C++ program to rotate a linked list
// by changing pointer of kth node

#include <iostream>
using namespace std;

class Node {
  public:
    int data;
    Node *next;

    Node(int new_data) {
        data = new_data;
        next = nullptr;
    }
};

// Function to rotate the linked list
// to the left by k places
Node *rotate(Node *head, int k) {

    // If the linked list is empty or no rotations are
    // needed, then return the original linked list
    if (k == 0 || head == nullptr)
        return head;

    Node *curr = head;
    int len = 1;
  
      // Find the length of linked list
    while (curr->next != nullptr) {
        curr = curr->next;
        len += 1;
    }

      // Modulo k with length of linked list to handle
      // large values of k
    k %= len;
  
    if (k == 0)
        return head;
  
      // Make the linked list circular
    curr->next = head;

      // Traverse the linked list to find the kth node
    curr = head;
    for (int i = 1; i < k; i++)
        curr = curr->next;

      // Update the (k + 1)th node as the new head
    head = curr->next;
  
      // Break the loop by updating next pointer of kth node
    curr->next = nullptr;
    return head;
}

void printList(Node *node) {
    while (node != nullptr) {
        cout << node->data << " ";
        node = node->next;
    }
    cout << endl;
}

int main() {

    // Create a hard-coded linked list:
    // 10 -> 20 -> 30 -> 40
    Node *head = new Node(10);
    head->next = new Node(20);
    head->next->next = new Node(30);
    head->next->next->next = new Node(40);
  
    head = rotate(head, 6);
    printList(head);
    return 0;
}
C
// C program to rotate a linked list
// by changing pointer of kth node

#include <stdio.h>

struct Node {
    int data;
    struct Node *next;
};

// Function to create a new node
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;
}

// Function to rotate the linked list
// to the left by k places
struct Node* rotate(struct Node *head, int k) {
  
    // If the linked list is empty or no rotations are
    // needed, then return the original linked list
    if (k == 0 || head == NULL)
        return head;

    struct Node *curr = head;
    int len = 1;

    // Find the length of linked list
    while (curr->next != NULL) {
        curr = curr->next;
        len += 1;
    }

    // Modulo k with length of linked list to handle
    // large values of k
    k %= len;

    if (k == 0)
        return head;
  
      // Make the linked list circular
    curr->next = head;

    // Traverse the linked list to find the kth node
    curr = head;
    for (int i = 1; i < k; i++)
        curr = curr->next;

    // Update the (k + 1)th node as the new head
    head = curr->next;

    // Break the loop by updating next pointer of kth node
    curr->next = NULL;
    return head;
}

void printList(struct Node *node) {
    while (node != NULL) {
        printf("%d ", node->data);
        node = node->next;
    }
    printf("\n");
}

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

    head = rotate(head, 6);
    printList(head);
    return 0;
}
Java
// Java program to rotate a linked list
// by changing pointer of kth node

class Node {
    int data;
    Node next;

    Node(int new_data) {
        data = new_data;
        next = null;
    }
}

// Function to rotate the linked list
// to the left by k places
class GfG {
    static Node rotate(Node head, int k) {

        // If the linked list is empty or no rotations are
        // needed, then return the original linked list
        if (k == 0 || head == null)
            return head;

        Node curr = head;
        int len = 1;
      
        // Find the length of linked list
        while (curr.next != null) {
            curr = curr.next;
            len += 1;
        }

        // Modulo k with length of linked list to handle
        // large values of k
        k %= len;
      
        if (k == 0)
            return head;
      
          // Make the linked list circular
        curr.next = head;

        // Traverse the linked list to find the kth node
        curr = head;
        for (int i = 1; i < k; i++)
            curr = curr.next;

        // Update the (k + 1)th node as the new head
        head = curr.next;
      
        // Break the loop by updating next pointer of kth node
        curr.next = null;
        return head;
    }

    static void printList(Node node) {
        while (node != null) {
            System.out.print(node.data + " ");
            node = node.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {

        // Create a hard-coded linked list:
        // 10 -> 20 -> 30 -> 40
        Node head = new Node(10);
        head.next = new Node(20);
        head.next.next = new Node(30);
        head.next.next.next = new Node(40);
      
        head = rotate(head, 6);
        printList(head);
    }
}
Python
# Python program to rotate a linked list
# by changing pointer of kth node

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

# Function to rotate the linked list
# to the left by k places
def rotate(head, k):

    # If the linked list is empty or no rotations are
    # needed, then return the original linked list
    if k == 0 or head is None:
        return head

    curr = head
    length = 1

    # Find the length of linked list
    while curr.next is not None:
        curr = curr.next
        length += 1

    # Modulo k with length of linked list to handle
    # large values of k
    k %= length

    if k == 0:
        curr.next = None
        return head
      
    # Make the linked list circular
    curr.next = head

    # Traverse the linked list to find the kth node
    curr = head
    for _ in range(1, k):
        curr = curr.next

    # Update the (k + 1)th node as the new head
    new_head = curr.next

    # Break the loop by updating next pointer of kth node
    curr.next = None
    return new_head

def print_list(node):
    while node is not None:
        print(node.data, end=" ")
        node = node.next
    print()

if __name__ == "__main__":

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

    head = rotate(head, 6)
    print_list(head)
C#
// C program to rotate a linked list
// by changing pointer of kth node

using System;

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

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

// Function to rotate the linked list
// to the left by k places
class GfG {

    static Node Rotate(Node head, int k) {

        // If the linked list is empty or no rotations are
        // needed, then return the original linked list
        if (k == 0 || head == null)
            return head;

        Node curr = head;
        int len = 1;
      
        // Find the length of linked list
        while (curr.next != null) {
            curr = curr.next;
            len += 1;
        }

        // Modulo k with length of linked list to handle
        // large values of k
        k %= len;
      
        if (k == 0) 
            return head;
      
          // Make the linked list circular
        curr.next = head;

        // Traverse the linked list to find the kth node
        curr = head;
        for (int i = 1; i < k; i++)
            curr = curr.next;

        // Update the (k + 1)th node as the new head
        Node newHead = curr.next;
      
        // Break the loop by updating next pointer of kth node
        curr.next = null;
        return newHead;
    }

    static void PrintList(Node node) {
        while (node != null) {
            Console.Write(node.data + " ");
            node = node.next;
        }
        Console.WriteLine();
    }

    public static void Main() {

        // Create a hard-coded linked list:
        // 10 -> 20 -> 30 -> 40
        Node head = new Node(10);
        head.next = new Node(20);
        head.next.next = new Node(30);
        head.next.next.next = new Node(40);
      
        head = Rotate(head, 6);
        PrintList(head);
    }
}
JavaScript
// JavaScript program to rotate a linked list
// by changing pointer of kth node

class Node {
    constructor(new_data) {
        this.data = new_data;
        this.next = null;
    }
}

// Function to rotate the linked list
// to the left by k places
function rotate(head, k) {

    // If the linked list is empty or no rotations are
    // needed, then return the original linked list
    if (k === 0 || head === null)
        return head;

    let curr = head;
    let len = 1;

    // Find the length of linked list
    while (curr.next !== null) {
        curr = curr.next;
        len += 1;
    }

    // Modulo k with length of linked list to handle
    // large values of k
    k %= len;

    if (k === 0) {
        curr.next = null;
        return head;
    }
    
    // Make the linked list circular
    curr.next = head;

    // Traverse the linked list to find the kth node
    curr = head;
    for (let i = 1; i < k; i++)
        curr = curr.next;

    // Update the (k + 1)th node as the new head
    let newHead = curr.next;

    // Break the loop by updating next pointer of kth node
    curr.next = null;
    return newHead;
}

function printList(node) {
    let output = '';
    while (node !== null) {
        output += node.data + ' ';
        node = node.next;
    }
    console.log(output.trim());
}

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

head = rotate(head, 6);
printList(head);

Output
30 40 10 20 

Time Complexity: O(n), where n is the number of nodes in linked list.
Auxiliary Space: O(1)



Similar Reads

Rotate the sub-list of a linked list from position M to N to the right by K places
Given a linked list and two positions 'm' and 'n'. The task is to rotate the sublist from position m to n, to the right by k places.Examples: Input: list = 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6, m = 2, n = 5, k = 2 Output: 1-&gt;4-&gt;5-&gt;2-&gt;3-&gt;6 Rotate the sublist 2 3 4 5 towards right 2 times then the modified list are: 1 4 5 2 3 6 Input: list
13 min read
Javascript Program for Rotate Doubly linked list by N nodes
Given a doubly linked list, rotate the linked list counter-clockwise by N nodes. Here N is a given positive integer and is smaller than the count of nodes in linked list. N = 2Rotated List: Examples: Input : a b c d e N = 2 Output : c d e a b Input : a b c d e f g h N = 4 Output : e f g h a b c d Asked in Amazon To rotate the Doubly linked list, we
4 min read
Javascript Program to Rotate Linked List block wise
Given a Linked List of length n and block length k rotate in a circular manner towards right/left each block by a number d. If d is positive rotate towards right else rotate towards left. Examples:  Input: 1->2->3->4->5->6->7->8->9->NULL, k = 3 d = 1 Output: 3->1->2->6->4->5->9->7->8->NULL Explanation: Here blocks of size 3 are rotated towards righ
4 min read
Left rotate Linked List by X in groups of Y nodes
Given a singly linked list and two integers X and Y, the task is to left rotate the linked list by X in groups of Y nodes. Examples: Input: 10 -&gt; 20 -&gt; 30 -&gt; 40 -&gt; 50 -&gt; 60 -&gt; 70 -&gt; 80 -&gt; 90 -&gt; 100, X = 2, Y = 4Output: 30 -&gt; 40 -&gt; 10 -&gt; 20 -&gt; 70 -&gt; 80 -&gt; 50 -&gt; 60 -&gt; 90 -&gt; 100Explanation: First g
10 min read
Rotate Linked List block wise
Given a Linked List of length n and block length k rotate in a circular manner towards right/left each block by a number d. If d is positive rotate towards right else rotate towards left. Examples: Input: 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6-&gt;7-&gt;8-&gt;9-&gt;NULL, k = 3 d = 1 Output: 3-&gt;1-&gt;2-&gt;6-&gt;4-&gt;5-&gt;9-&gt;7-&gt;8-&gt;NULL Explan
14 min read
Rotate Doubly linked list by N nodes
Given a doubly-linked list, rotate the linked list counter-clockwise by N nodes. Here N is a given positive integer and is smaller than the count of nodes in linked list.  N = 2Rotated List:  Examples:   Input : a b c d e N = 2Output : c d e a b Input : a b c d e f g h N = 4Output : e f g h a b c d Asked in Amazon  Solution 1: [GFGTABS] C++ #includ
15+ 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 &lt; – &gt; 7 &lt; – &gt; 9 &lt; – &gt; 7 Output: 7 &lt; – &gt; 9 &lt; – &gt; 7 Explanation: Removing the first node of the XOR linked list modifies XLL to 7 &lt; – &gt; 9 &lt; – &gt; 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 -&gt; 3 -&gt; 4 -&gt; 5 -&gt; 3 -&gt; 4, head2 = 3 -&gt; 4Output: 2 -&gt; 5Explanation: After removing all occurrences of 3 -&gt; 4 in head1 output is 2 -&gt; 5. Input: head1 = 3 -&gt; 6 -&gt; 9 -&gt; 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-&gt;2-&gt;3-&gt;2-&gt;4-&gt;5-&gt;2-&gt;4, Head2 = 2-&gt;4Output: Occurrences of head2 in head1: 2 Input: Head1 = 3-&gt;4-&gt;1-&gt;5-&gt;2, Head2 = 3-&gt;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&lt; – &gt; 6 &lt; – &gt; 8 &lt; – &gt; 11 &lt; – &gt; 3, K = 3 Output: 8 &lt; – &gt; 6 &lt; – &gt; 7 &lt; – &gt; 3 &lt; – &gt; 11 Explanation: Reversing first K(= 3) nodes modifies the Linked List to 8 &lt; – &gt; 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&lt;–&gt;7&lt;–&gt;9&lt;–&gt;7Output: 4&lt;–&gt;7&lt;–&gt;9Explanation: Deleting a node from the end modifies the given XOR Linked List to 4&lt;–&gt;7&lt;–&gt;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
XOR Linked List - Pairwise swap elements of a given linked list
Given a XOR linked list, the task is to pairwise swap the elements of the given XOR linked list . Examples: Input: 4 &lt;-&gt; 7 &lt;-&gt; 9 &lt;-&gt; 7Output: 7 &lt;-&gt; 4 &lt;-&gt; 7 &lt;-&gt; 9Explanation:First pair of nodes are swapped to formed the sequence {4, 7} and second pair of nodes are swapped to form the sequence {9, 7}. Input: 1 &lt;
12 min read
XOR linked list: Reverse last K nodes of a Linked List
Given a XOR Linked List and a positive integer K, the task is to reverse the last K nodes in the given XOR linked list. Examples: Input: LL: 7 &lt;–&gt; 6 &lt;–&gt; 8 &lt;–&gt; 11 &lt;–&gt; 3 &lt;–&gt; 1, K = 3Output: 7&lt;–&gt;6&lt;–&gt;8&lt;–&gt;1&lt;–&gt;3&lt;–&gt;11 Input: LL: 7 &lt;–&gt; 6 &lt;–&gt; 8 &lt;–&gt; 11 &lt;–&gt; 3 &lt;–&gt; 1 &lt;–
14 min read
XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
In this post, we're going to talk about how XOR linked lists are used to reduce the memory requirements of doubly-linked lists. We know that each node in a doubly-linked list has two pointer fields which contain the addresses of the previous and next node. On the other hand, each node of the XOR linked list requires only a single pointer field, whi
15+ min read
Linked List of Linked List
Linked list of linke­d list, also known as nested linke­d lists, is a type of Linked List where each main node stores another full linked list. This structure­ beats old, plain linked lists. It gives way more­ flexibility to store and manage comple­x data. In this article we will learn about the basics of Linked List of Linked List, how to create L
9 min read
XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
In the previous post, we discussed how a Doubly Linked can be created using only one space for the address field with every node. In this post, we will discuss the implementation of a memory-efficient doubly linked list. We will mainly discuss the following two simple functions. A function to insert a new node at the beginning.A function to travers
10 min read
Create new linked list from two given linked list with greater element at each node
Given two linked list of the same size, the task is to create a new linked list using those linked lists. The condition is that the greater node among both linked list will be added to the new linked list.Examples: Input: list1 = 5-&gt;2-&gt;3-&gt;8list2 = 1-&gt;7-&gt;4-&gt;5Output: New list = 5-&gt;7-&gt;4-&gt;8Input: list1 = 2-&gt;8-&gt;9-&gt;3li
8 min read
Difference between Singly linked list and Doubly linked list
Introduction to Singly linked list : A singly linked list is a set of nodes where each node has two fields 'data' and 'link'. The 'data' field stores actual piece of information and 'link' field is used to point to next node. Basically the 'link' field stores the address of the next node.  Introduction to Doubly linked list : A Doubly Linked List (
2 min read
Check if a linked list is Circular Linked List
Given the head of a singly linked list, the task is to find if given linked list is circular or not. A linked list is called circular if its last node points back to its first node. Note: The linked list does not contain any internal loops. Example: Input: LinkedList: 2-&gt;4-&gt;6-&gt;7-&gt;5 Output: trueExplanation: As shown in figure the first a
12 min read
Javascript Program To Merge A Linked List Into Another Linked List At Alternate Positions
Given two linked lists, insert nodes of the second list into the first list at alternate positions of the first list. For example, if first list is 5-&gt;7-&gt;17-&gt;13-&gt;11 and second is 12-&gt;10-&gt;2-&gt;4-&gt;6, the first list should become 5-&gt;12-&gt;7-&gt;10-&gt;17-&gt;2-&gt;13-&gt;4-&gt;11-&gt;6 and second list should become empty. The
3 min read
Insert a linked list into another linked list
Given two linked lists, head1 and head2 of sizes m and n respectively. The task is to remove head1's nodes from the ath node to the bth node and insert head2 in their place. Examples: Input: a = 3, b = 4head1: 10 -&gt; 11 -&gt; 12 -&gt; 13 -&gt; 14 -&gt; 15, head2: 100 -&gt; 101 -&gt; 102 -&gt; 103Output: 10 -&gt; 11 -&gt; 12 -&gt; 100 -&gt; 101 -
10 min read
Convert singly linked list into circular linked list
Given a singly linked list, the task is to convert it into a circular linked list. Examples: Input: head: 1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; 5 -&gt; 6 -&gt; NULLOutput: Explanation: Singly linked list is converted to circular by pointing last node to head. Input: head: 2 -&gt; 4 -&gt; 6 -&gt; 8 -&gt; 10 -&gt; 12 -&gt; NULLOutput: Explanation: Singly l
11 min read
Merge a linked list into another linked list at alternate positions
Given two singly linked lists, The task is to insert nodes of the second list into the first list at alternate positions of the first list and leave the remaining nodes of the second list if it is longer. Example: Input: head1: 1-&gt;2-&gt;3 , head2: 4-&gt;5-&gt;6-&gt;7-&gt;8Output: head1: 1-&gt;4-&gt;2-&gt;5-&gt;3-&gt;6 , head2: 7-&gt;8 Input: hea
8 min read
Python | Ways to rotate a list
The rotation of a list has been discussed earlier also, but this particular article focuses on shorthands and various short techniques to achieve this in one-liners or one word. This operation is quite essential in a programmer's life to achieve various tasks. Let's discuss different ways we can rotate a list in Python. Method 1: Rotate a list usin
8 min read
Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
Given two sorted linked lists, construct a linked list that contains maximum sum path from start to end. The result list may contain nodes from both input lists. When constructing the result list, we may switch to the other input list only at the point of intersection (which mean the two node with the same value in the lists). You are allowed to us
14 min read
Create a linked list from two linked lists by choosing max element at each position
Given two linked list of equal sizes, the task is to create new linked list using those linked lists where at every step, the maximum of the two elements from both the linked lists is chosen and the other is skipped. Examples: Input: list1 = 5 -&gt; 2 -&gt; 3 -&gt; 8 -&gt; NULL list2 = 1 -&gt; 7 -&gt; 4 -&gt; 5 -&gt; NULL Output: 5 -&gt; 7 -&gt; 4
11 min read
Construct a Doubly linked linked list from 2D Matrix
Given a 2D matrix, the task is to convert it into a doubly-linked list with four pointers that are next, previous, up, and down, each node of this list should be connected to its next, previous, up, and down nodes.Examples: Input: 2D matrix 1 2 3 4 5 6 7 8 9 Output: Approach: The main idea is to construct a new node for every element of the matrix
15+ min read
Article Tags :