The Wayback Machine - https://web.archive.org/web/20240922034607/https://www.geeksforgeeks.org/exchange-first-last-node-circular-linked-list/
Open In App

Exchange first and last nodes in Circular Linked List

Last Updated : 22 Feb, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given Circular linked list exchange the first and the last node. The task should be done with only one extra node, you can not declare more than one extra node, and also you are not allowed to declare any other temporary variable. 

Note: Extra node means the need of a node to traverse a list.  

https://media.geeksforgeeks.org/wp-content/uploads/Capturehgh.png

Examples: 

Input : 5 4 3 2 1
Output : 1 4 3 2 5

Input  : 6 1 2 3 4 5 6 7 8 9
Output : 9 1 2 3 4 5 6 7 8 6

Method 1: (By Changing Links of First and Last Nodes)

We first find a pointer to the previous to the last node. Let this node be p. Now we change the next links so that the last and first nodes are swapped.  

C++




// CPP program to exchange first and
// last node in circular linked list
#include <bits/stdc++.h>
using namespace std;
 
struct Node {
    int data;
    struct Node* next;
};
 
struct Node* addToEmpty(struct Node* head, int data)
{
    // This function is only for empty list
    if (head != NULL)
        return head;
 
    // Creating a node dynamically.
    struct Node* temp
        = (struct Node*)malloc(sizeof(struct Node));
 
    // Assigning the data.
    temp->data = data;
    head = temp;
 
    // Creating the link.
    head->next = head;
 
    return head;
}
 
struct Node* addBegin(struct Node* head, int data)
{
    if (head == NULL)
        return addToEmpty(head, data);
 
    struct Node* temp
        = (struct Node*)malloc(sizeof(struct Node));
 
    temp->data = data;
    temp->next = head->next;
    head->next = temp;
 
    return head;
}
 
/* function for traversing the list */
void traverse(struct Node* head)
{
    struct Node* p;
 
    // If list is empty, return.
    if (head == NULL) {
        cout << "List is empty." << endl;
        return;
    }
 
    // Pointing to first Node of the list.
    p = head;
 
    // Traversing the list.
    do {
        cout << p->data << " ";
        p = p->next;
 
    } while (p != head);
}
 
/* Function to exchange first and last node*/
struct Node* exchangeNodes(struct Node* head)
{
    // If list is of length 2
    if (head->next->next == head) {
        head = head->next;
        return head;
    }
 
    // Find pointer to previous of last node
    struct Node* p = head;
    while (p->next->next != head)
        p = p->next;
 
    /* Exchange first and last nodes using
       head and p */
    p->next->next = head->next;
    head->next = p->next;
    p->next = head;
    head = head->next;
 
    return head;
}
 
// Driven Program
int main()
{
    int i;
    struct Node* head = NULL;
    head = addToEmpty(head, 6);
 
    for (i = 5; i > 0; i--)
        head = addBegin(head, i);
    cout << "List Before: ";
    traverse(head);
    cout << endl;
 
    cout << "List After: ";
    head = exchangeNodes(head);
    traverse(head);
 
    return 0;
}


Java




// Java program to exchange
// first and last node in
// circular linked list
import java.util.*;
import java.io.*;
 
public class GFG {
 
    static class Node {
        int data;
        Node next;
    };
 
    static Node addToEmpty(Node head, int data)
    {
        // This function is only
        // for empty list
        if (head != null)
            return head;
 
        // Creating a node dynamically.
        Node temp = new Node();
 
        // Assigning the data.
        temp.data = data;
        head = temp;
 
        // Creating the link.
        head.next = head;
 
        return head;
    }
 
    static Node addBegin(Node head, int data)
    {
        if (head == null)
            return addToEmpty(head, data);
 
        Node temp = new Node();
 
        temp.data = data;
        temp.next = head.next;
        head.next = temp;
 
        return head;
    }
 
    // function for traversing the list
    static void traverse(Node head)
    {
        Node p;
 
        // If list is empty, return.
        if (head == null) {
            System.out.print("List is empty.");
            return;
        }
 
        // Pointing to first
        // Node of the list.
        p = head;
 
        // Traversing the list.
        do {
            System.out.print(p.data + " ");
            p = p.next;
 
        } while (p != head);
    }
 
    // Function to exchange
    // first and last node
    static Node exchangeNodes(Node head)
    {
 
        // If list is of length 2
        if (head.next.next == head) {
            head = head.next;
            return head;
        }
        // Find pointer to previous
        // of last node
        Node p = head;
        while (p.next.next != head)
            p = p.next;
 
        // Exchange first and last
        // nodes using head and p
        p.next.next = head.next;
        head.next = p.next;
        p.next = head;
        head = head.next;
 
        return head;
    }
 
    // Driver Code
    public static void main(String args[])
    {
        int i;
        Node head = null;
        head = addToEmpty(head, 6);
 
        for (i = 5; i > 0; i--)
            head = addBegin(head, i);
        System.out.print("List Before: ");
        traverse(head);
        System.out.println();
 
        System.out.print("List After: ");
        head = exchangeNodes(head);
        traverse(head);
    }
}
 
// This code is contributed
// by Arnab Kundu


Python3




# Python3 program to exchange first and
# last node in circular linked list
import math
 
 
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
 
 
def addToEmpty(head, data):
 
    # This function is only for empty list
    if (head != None):
        return head
 
    # Creating a node dynamically.
    temp = Node(data)
 
    # Assigning the data.
    temp.data = data
    head = temp
 
    # Creating the link.
    head.next = head
    return head
 
 
def addBegin(head, data):
 
    if (head == None):
        return addToEmpty(head, data)
 
    temp = Node(data)
    temp.data = data
    temp.next = head.next
    head.next = temp
 
    return head
 
# function for traversing the list
 
 
def traverse(head):
 
    # If list is empty, return.
    if (head == None):
 
        print("List is empty.")
        return
 
    # Pointing to first Node of the list.
    p = head
    print(p.data, end=" ")
    p = p.next
 
    # Traversing the list.
    while(p != head):
 
        print(p.data, end=" ")
        p = p.next
 
 
def exchangeNodes(head):
 
    # Cases Handled: Linked List either empty or containing single node.
    if head == None or head.next == head:
        return head
    # Cases Handled: Linked List containing only two nodes
    elif head.next.next == head:
        head = head.next
        return head
    # Cases Handled: Linked List containing multiple nodes
    else:
        prev = None
        curr = head
        temp = head
        # finding last and second last nodes in linkedlist list
        while curr.next != head:
            prev = curr
            curr = curr.next
 
        # point the last node to second node of the list
        curr.next = temp.next
        # point the second last node to first node
        prev.next = temp
        # point the end of node to start ( make linked list circular )
        temp.next = curr
        # mark the starting of linked list
        head = curr
 
        return head
 
 
# Driver Code
if __name__ == '__main__':
 
    head = None
    head = addToEmpty(head, 6)
    for x in range(5, 0, -1):
        head = addBegin(head, x)
    print("List Before: ", end="")
    traverse(head)
    print()
 
    print("List After: ", end="")
    head = exchangeNodes(head)
    traverse(head)
 
# This code is contributed by Srathore
# Improved by Vinay Kumar (vinaykumar71)


C#




// C# program to exchange
// first and last node in
// circular linked list
using System;
 
public class GFG {
 
    class Node {
        public int data;
        public Node next;
    };
 
    static Node addToEmpty(Node head, int data)
    {
        // This function is only
        // for empty list
        if (head != null)
            return head;
 
        // Creating a node dynamically.
        Node temp = new Node();
 
        // Assigning the data.
        temp.data = data;
        head = temp;
 
        // Creating the link.
        head.next = head;
 
        return head;
    }
 
    static Node addBegin(Node head, int data)
    {
        if (head == null)
            return addToEmpty(head, data);
 
        Node temp = new Node();
 
        temp.data = data;
        temp.next = head.next;
        head.next = temp;
 
        return head;
    }
 
    // function for traversing the list
    static void traverse(Node head)
    {
        Node p;
 
        // If list is empty, return.
        if (head == null) {
            Console.Write("List is empty.");
            return;
        }
 
        // Pointing to first
        // Node of the list.
        p = head;
 
        // Traversing the list.
        do {
            Console.Write(p.data + " ");
            p = p.next;
 
        } while (p != head);
    }
 
    // Function to exchange
    // first and last node
    static Node exchangeNodes(Node head)
    {
 
        // If list is of length 2
        if (head.next.next == head) {
            head = head.next;
            return head;
        }
        // Find pointer to previous
        // of last node
        Node p = head;
        while (p.next.next != head)
            p = p.next;
 
        // Exchange first and last
        // nodes using head and p
        p.next.next = head.next;
        head.next = p.next;
        p.next = head;
        head = head.next;
 
        return head;
    }
 
    // Driver Code
    public static void Main()
    {
        int i;
        Node head = null;
        head = addToEmpty(head, 6);
 
        for (i = 5; i > 0; i--)
            head = addBegin(head, i);
        Console.Write("List Before: ");
        traverse(head);
        Console.WriteLine();
 
        Console.Write("List After: ");
        head = exchangeNodes(head);
        traverse(head);
    }
}
 
/* This code is contributed PrinciRaj1992 */


Javascript




<script>
// javascript program to exchange
// first and last node in
// circular linked list   
 
class Node {
    constructor() {
        this.data = 0;
        this.next = null;
    }
}
    function addToEmpty(head , data) {
        // This function is only
        // for empty list
        if (head != null)
            return head;
 
        // Creating a node dynamically.
        var temp = new Node();
 
        // Assigning the data.
        temp.data = data;
        head = temp;
 
        // Creating the link.
        head.next = head;
 
        return head;
    }
 
    function addBegin(head , data) {
        if (head == null)
            return addToEmpty(head, data);
 
        var temp = new Node();
 
        temp.data = data;
        temp.next = head.next;
        head.next = temp;
 
        return head;
    }
 
    // function for traversing the list
    function traverse(head) {
    var p;
 
        // If list is empty, return.
        if (head == null) {
            document.write("List is empty.");
            return;
        }
 
        // Pointing to first
        // Node of the list.
        p = head;
 
        // Traversing the list.
        do {
            document.write(p.data + " ");
            p = p.next;
 
        } while (p != head);
    }
 
    // Function to exchange
    // first and last node
    function exchangeNodes(head) {
 
        // If list is of length 2
        if (head.next.next == head) {
            head = head.next;
            return head;
        }
        // Find pointer to previous
        // of last node
        var p = head;
        while (p.next.next != head)
            p = p.next;
 
        // Exchange first and last
        // nodes using head and p
        p.next.next = head.next;
        head.next = p.next;
        p.next = head;
        head = head.next;
 
        return head;
    }
 
    // Driver Code
     
        var i;
        var head = null;
        head = addToEmpty(head, 6);
 
        for (i = 5; i > 0; i--)
            head = addBegin(head, i);
        document.write("List Before: ");
        traverse(head);
        document.write("<br/>");
 
        document.write("List After: ");
        head = exchangeNodes(head);
        traverse(head);
 
// This code is contributed by umadevi9616
</script>


Output

List Before: 6 1 2 3 4 5 
List After: 5 1 2 3 4 6 

Time Complexity: O(n), as we are using a loop to traverse n times. Where n is the number of nodes in the linked list.
Auxiliary Space: O(1), as we are not using any extra space.

Method 2: (By Swapping Values of First and Last nodes)

Algorithm: 

  1. Traverse the list and find the last node(tail).
  2. Swap data of head and tail.

Below is the implementation of the algorithm:

C++




// CPP program to exchange first and
// last node in circular linked list
#include <bits/stdc++.h>
using namespace std;
 
struct Node {
    int data;
    struct Node* next;
};
 
struct Node* addToEmpty(struct Node* head, int data)
{
    // This function is only for empty list
    if (head != NULL)
        return head;
 
    // Creating a node dynamically.
    struct Node* temp
        = (struct Node*)malloc(sizeof(struct Node));
 
    // Assigning the data.
    temp->data = data;
    head = temp;
 
    // Creating the link.
    head->next = head;
 
    return head;
}
 
struct Node* addBegin(struct Node* head, int data)
{
    if (head == NULL)
        return addToEmpty(head, data);
 
    struct Node* temp
        = (struct Node*)malloc(sizeof(struct Node));
 
    temp->data = data;
    temp->next = head->next;
    head->next = temp;
 
    return head;
}
 
/* function for traversing the list */
void traverse(struct Node* head)
{
    struct Node* p;
 
    // If list is empty, return.
    if (head == NULL) {
        cout << "List is empty." << endl;
        return;
    }
 
    // Pointing to first Node of the list.
    p = head;
 
    // Traversing the list.
    do {
        cout << p->data << " ";
        p = p->next;
 
    } while (p != head);
}
 
/* Function to exchange first and last node*/
struct Node* exchangeNodes(struct Node* head)
{
     
    // If list is of length less than 2
    if (head == NULL || head->next == NULL) {
        return head;
    }
    Node* tail = head;
   
    // Find pointer to the last node
    while (tail->next != head) {
        tail = tail->next;
    }
    /* Exchange first and last nodes using
       head and p */
   
    // temporary variable to store
    // head data
    int temp = tail->data;
    tail->data = head->data;
    head->data = temp;
    return head;
}
 
// Driven Program
int main()
{
    int i;
    struct Node* head = NULL;
    head = addToEmpty(head, 6);
 
    for (i = 5; i > 0; i--)
        head = addBegin(head, i);
    cout << "List Before: ";
    traverse(head);
    cout << endl;
 
    cout << "List After: ";
    head = exchangeNodes(head);
    traverse(head);
 
    return 0;
}


Java




// JAVA program to exchange first and
// last node in circular linked list
import java.util.*;
import java.io.*;
 
public class GFG{
 
static class Node {
    int data;
    Node next;
};
 
static Node addToEmpty(Node head, int data)
{
   
    // This function is only for empty list
    if (head != null)
        return head;
 
    // Creating a node dynamically.
    Node temp
        = new Node();
 
    // Assigning the data.
    temp.data = data;
    head = temp;
 
    // Creating the link.
    head.next = head;
 
    return head;
}
 
static Node addBegin(Node head, int data)
{
    if (head == null)
        return addToEmpty(head, data);
 
    Node temp
        = new Node();
 
    temp.data = data;
    temp.next = head.next;
    head.next = temp;
 
    return head;
}
 
/* function for traversing the list */
static void traverse(Node head)
{
    Node p;
 
    // If list is empty, return.
    if (head == null) {
        System.out.print("List is empty." +"\n");
        return;
    }
 
    // Pointing to first Node of the list.
    p = head;
 
    // Traversing the list.
    do {
        System.out.print(p.data+ " ");
        p = p.next;
 
    } while (p != head);
}
 
/* Function to exchange first and last node*/
static Node exchangeNodes(Node head)
{
     
    // If list is of length less than 2
    if (head == null || head.next == null) {
        return head;
    }
    Node tail = head;
   
    // Find pointer to the last node
    while (tail.next != head) {
        tail = tail.next;
    }
    /* Exchange first and last nodes using
       head and p */
   
    // temporary variable to store
    // head data
    int temp = tail.data;
    tail.data = head.data;
    head.data = temp;
    return head;
}
 
// Driven Program
public static void main(String[] args)
{
    int i;
    Node head = null;
    head = addToEmpty(head, 6);
 
    for (i = 5; i > 0; i--)
        head = addBegin(head, i);
    System.out.print("List Before: ");
    traverse(head);
    System.out.println();
 
    System.out.print("List After: ");
    head = exchangeNodes(head);
    traverse(head);
 
}
}
 
// This code is contributed by umadevi9616


Python3




# Python program to exchange first and
# last node in circular linked list     class Node {
class Node:
    def __init__(self):
        self.data = 0
        self.next = None
 
def addToEmpty(head, data):
 
    # This function is only for empty list
    if (head != None):
        return head
 
    # Creating a node dynamically.
    temp = Node()
 
    # Assigning the data.
    temp.data = data
    head = temp
 
    # Creating the link.
    head.next = head
 
    return head
 
def addBegin(head, data):
    if (head == None):
        return addToEmpty(head, data)
 
    temp = Node()
 
    temp.data = data
    temp.next = head.next
    head.next = temp
 
    return head
 
# function for traversing the list
def traverse(head):
 
    # If list is empty, return.
    if (head == None):
        print("List is empty.")
        return
 
    # Pointing to first Node of the list.
    p = head
 
    # Traversing the list.
    while (True):
        print(p.data, end=" ")
        p = p.next
        if(p == head):
            break
 
# Function to exchange first and last node
def exchangeNodes(head):
 
    # If list is of length less than 2
    if (head == None or head.next == None):
        return head
 
    tail = head
 
    # Find pointer to the last node
    while (tail.next != head):
        tail = tail.next
 
    # Exchange first and last nodes using head and p
 
    # temporary variable to store
    # head data
    temp = tail.data
    tail.data = head.data
    head.data = temp
    return head
 
# Driven Program
head = None
head = addToEmpty(head, 6)
 
for i in range(5, 0, -1):
    head = addBegin(head, i)
 
print("List Before: ")
traverse(head)
print("")
 
print("List After: ")
head = exchangeNodes(head)
traverse(head)
 
# This code is contributed by Saurabh Jaiswal


C#




// C# program to exchange first and
// last node in circular linked list
using System;
 
public class GFG {
 
public    class Node {
    public    int data;
    public    Node next;
    };
 
    static Node addToEmpty(Node head, int data) {
 
        // This function is only for empty list
        if (head != null)
            return head;
 
        // Creating a node dynamically.
        Node temp = new Node();
 
        // Assigning the data.
        temp.data = data;
        head = temp;
 
        // Creating the link.
        head.next = head;
 
        return head;
    }
 
    static Node addBegin(Node head, int data) {
        if (head == null)
            return addToEmpty(head, data);
 
        Node temp = new Node();
 
        temp.data = data;
        temp.next = head.next;
        head.next = temp;
 
        return head;
    }
 
    /* function for traversing the list */
    static void traverse(Node head) {
        Node p;
 
        // If list is empty, return.
        if (head == null) {
            Console.Write("List is empty." + "\n");
            return;
        }
 
        // Pointing to first Node of the list.
        p = head;
 
        // Traversing the list.
        do {
            Console.Write(p.data + " ");
            p = p.next;
 
        } while (p != head);
    }
 
    /* Function to exchange first and last node */
    static Node exchangeNodes(Node head) {
 
        // If list is of length less than 2
        if (head == null || head.next == null) {
            return head;
        }
        Node tail = head;
 
        // Find pointer to the last node
        while (tail.next != head) {
            tail = tail.next;
        }
        /*
         * Exchange first and last nodes using head and p
         */
 
        // temporary variable to store
        // head data
        int temp = tail.data;
        tail.data = head.data;
        head.data = temp;
        return head;
    }
 
    // Driven Program
    public static void Main(String[] args) {
        int i;
        Node head = null;
        head = addToEmpty(head, 6);
 
        for (i = 5; i > 0; i--)
            head = addBegin(head, i);
        Console.Write("List Before: ");
        traverse(head);
        Console.WriteLine();
 
        Console.Write("List After: ");
        head = exchangeNodes(head);
        traverse(head);
    }
}
 
// This code is contributed by umadevi9616


Javascript




<script>
// javascript program to exchange first and
// last node in circular linked list     class Node {
class Node {
    constructor() {
        this.data = 0;
        this.next = null;
    }
}
 
    function addToEmpty(head , data) {
 
        // This function is only for empty list
        if (head != null)
            return head;
 
        // Creating a node dynamically.
    var temp = new Node();
 
        // Assigning the data.
        temp.data = data;
        head = temp;
 
        // Creating the link.
        head.next = head;
 
        return head;
    }
 
    function addBegin(head , data) {
        if (head == null)
            return addToEmpty(head, data);
 
            var temp = new Node();
 
        temp.data = data;
        temp.next = head.next;
        head.next = temp;
 
        return head;
    }
 
    /* function for traversing the list */
    function traverse(head) {
    var p;
 
        // If list is empty, return.
        if (head == null) {
            document.write("List is empty." + "\n");
            return;
        }
 
        // Pointing to first Node of the list.
        p = head;
 
        // Traversing the list.
        do {
            document.write(p.data + " ");
            p = p.next;
 
        } while (p != head);
    }
 
    /* Function to exchange first and last node */
    function exchangeNodes(head) {
 
        // If list is of length less than 2
        if (head == null || head.next == null) {
            return head;
        }
var tail = head;
 
        // Find pointer to the last node
        while (tail.next != head) {
            tail = tail.next;
        }
        /*
         * Exchange first and last nodes using head and p
         */
 
        // temporary variable to store
        // head data
        var temp = tail.data;
        tail.data = head.data;
        head.data = temp;
        return head;
    }
 
    // Driven Program
     
        var i;
        var head = null;
        head = addToEmpty(head, 6);
 
        for (i = 5; i > 0; i--)
            head = addBegin(head, i);
        document.write("List Before: <br/>");
        traverse(head);
        document.write("<br/>");
 
        document.write("List After: <br/>");
        head = exchangeNodes(head);
        traverse(head);
 
// This code is contributed by umadevi9616
</script>


Output

List Before: 6 1 2 3 4 5 
List After: 5 1 2 3 4 6 

Time Complexity: O(n), as we are using a loop to traverse n times. Where n is the number of nodes in the linked list.
Auxiliary Space: O(1), as we are not using any extra space.

 



Similar Reads

Splitting starting N nodes into new Circular Linked List while preserving the old nodes
Given a circular linked list with N nodes and an integer K where 0 &lt; K &lt; N, the task is to split the first K nodes into a new list and at the same time preserving the rest of the nodes in the original circular linked list. Examples: Input: 2 -&gt; 3 -&gt; 4 -&gt; 5 -&gt; 6 -&gt; 7 -&gt; 8, K = 3 Output: Original list: 2 3 4 5 6 7 8 The new li
13 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
Circular Linked List Implementation of Circular Queue
Prerequisite – Circular Singly Linked List We have discussed basics and how to implement circular queue using array in set 1. Circular Queue | Set 1 (Introduction and Array Implementation) In this post another method of circular queue implementation is discussed, using Circular Singly Linked List. Operations on Circular Queue: Front:Get the front i
9 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
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
Sum and Product of the nodes of a Circular Singly Linked List which are divisible by K
Given a singly circular linked list. The task is to find the sum and product of nodes that are divisible by K of the given linked list. Examples: Input : List = 5-&gt;6-&gt;7-&gt;8-&gt;9-&gt;10-&gt;11-&gt;11 K = 11 Output : Sum = 22, Product = 121 Input : List = 15-&gt;7-&gt;3-&gt;9-&gt;11-&gt;5 K = 5 Output : Product = 75, Sum = 20 Approach: Initi
12 min read
Sum and Product of nodes with value as even digit sum in Circular Linked List
Given a circular singly linked list containing N nodes, The task is to find the sum and product of all the nodes from the list whose data value has an even digit sum. Examples: Input: List = 15 -&gt; 16 -&gt; 8 -&gt; 6 -&gt; 13 Output: Sum = 42, Product = 9360 Explanation: The circular linked list contains: 15 -&gt; 1 + 5 = 6 16 -&gt; 1 + 6 = 7 8 -
11 min read
Remove all even parity nodes from a Doubly and Circular Singly Linked List
Given a Doubly linked list and Circular singly linked list containing N nodes, the task is to remove all the nodes from each list which contains elements whose parity is even. Example: Input: CLL = 9 -&gt; 11 -&gt; 34 -&gt; 6 -&gt; 13 -&gt; 21 Output: 11 -&gt; 13 -&gt; 21 Explanation: The circular singly linked list contains : 11 -&gt; 1011, parity
15+ min read
Sum of the nodes of a Circular Linked List
Given a singly Circular linked list. The task is to find the sum of nodes of the given linked list. For the above circular list, sum = 2 + 5 + 7 + 8 + 10 = 32 Examples: Input: 11-&gt;2-&gt;56-&gt;12 Output: Sum of Circular linked list is = 81 Input: 2-&gt; 5 -&gt; 7 -&gt; 8 -&gt; 10 Output: Sum of Circular linked list is = 32 Approach: Initialize a
7 min read
Delete all the even nodes of a Circular Linked List
Given a circular singly linked list containing N nodes, the task is to delete all the even nodes from the list. Examples: Input : 57-&gt;11-&gt;2-&gt;56-&gt;12-&gt;61 Output : List after deletion : 57 -&gt; 11 -&gt; 61 Input : 9-&gt;11-&gt;32-&gt;6-&gt;13-&gt;20 Output : List after deletion : 9 -&gt; 11 -&gt; 13 The idea is to traverse the nodes of
10 min read
Delete all Prime Nodes from a Circular Singly Linked List
Given a circular singly linked list containing N nodes. The task is to delete all nodes from the list which are prime. Examples: Input : 9-&gt;11-&gt;32-&gt;6-&gt;13-&gt;20 Output : 9 32 6 20 Input : 6-&gt;11-&gt;16-&gt;21-&gt;17-&gt;10 Output : 6 16 21 10 Approach: The idea is to traverse the nodes of the circular singly linked list one by one and
13 min read
Delete all odd or even positioned nodes from Circular Linked List
Delete all odd or even position nodes from circular linked list Given a Singly Circular Linked List, starting from the first node delete all odd position nodes in it. Note: Linked list is considered to have 1-based indexing. That is, first element in the linked list is at position 1. Examples: Input : List = 99-&gt;11-&gt;22-&gt;33 Output : 11-&gt;
15+ min read
Delete all odd nodes of a Circular Linked List
Prerequisite: Delete all the even nodes of a Circular Linked ListGiven a circular singly linked list containing N nodes, the task is to delete all the odd nodes from the list. Examples: Input: 572-&gt;112-&gt;21-&gt;5-&gt;1-&gt;6 Output: 572 -&gt; 112 -&gt; 6 Explanation: All the odd valued nodes have been deletedInput: 9-&gt;11-&gt;32-&gt;6-&gt;13
10 min read
Remove all Fibonacci Nodes from a Circular Singly Linked List
Given a circular singly linked list containing N nodes, the task is to remove all the nodes from the list which contains Fibonacci data values.Examples: Input: CLL = 9 -&gt; 11 -&gt; 34 -&gt; 6 -&gt; 13 -&gt; 20 Output: 9 -&gt; 11 -&gt; 6 -&gt; 20 Explanation: The list contains 2 fibonacci data values 32 and 13. Therefore, the nodes containing this
15+ min read
Remove all the Even Digit Sum Nodes from a Circular Singly Linked List
Given a circular singly linked list containing N nodes, the task is to remove all the nodes from the list which contains elements whose digit sum is even. Examples: Input: CLL = 9 -&gt; 11 -&gt; 34 -&gt; 6 -&gt; 13 -&gt; 21 Output: 9 -&gt; 34 -&gt; 21 Explanation: The circular singly linked list contains : 9 -&gt; 9 11 -&gt; 1 + 1 = 2 34 -&gt; 3 +
12 min read
Modify a Circular Doubly Linked List such that each node stores the sum of all nodes except itself
Given a circular doubly linked list consisting of N nodes, the task is to modify every node of the given Linked List such that each node contains the sum of all nodes except that node. Examples: Input: 4 ↔ 5 ↔ 6 ↔7 ↔ 8Output: 26 ↔ 25 ↔ 24 ↔ 23 ↔ 22Explanation:1st Node: Sum of all nodes except itself = (5 + 6 + 7 + 8) = 26.2nd Node: Sum of all nodes
15+ min read
Count nodes in Circular linked list
Given a circular linked list. The task is to find the length of the linked list, where length is defined as the number of nodes in the linked list. Using linear traversal - O(n) time and O(1) spaceThe idea is to start from the head node and traversing the list until it loops back to the head. Since a circular linked list has no end, the traversal c
5 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
Find the product of last N nodes of the given Linked List
Given a linked list and a number N. Find the product of last n nodes of the linked list. Constraints : 0 &lt;= N &lt;= number of nodes in the linked list. Examples: Input : List = 10-&gt;6-&gt;8-&gt;4-&gt;12, N = 2 Output : 48 Explanation : Product of last two nodes: 12 * 4 = 48 Input : List = 15-&gt;7-&gt;9-&gt;5-&gt;16-&gt;14, N = 4 Output : 1008
15+ min read
Print the last k nodes of the linked list in reverse order | Recursive approach
Given a linked list containing N nodes and a positive integer k should be less than or equal to N. The task is to print the last k nodes of the list in reverse order. Examples: Input: list: 1-&gt;2-&gt;3-&gt;4-&gt;5, k = 2 Output: 5 4 Input: list: 3-&gt;10-&gt;6-&gt;9-&gt;12-&gt;2-&gt;8, k = 4 Output: 8 2 12 9 Source: Amazon Interview Experience SD
7 min read
Print the last k nodes of the linked list in reverse order | Iterative Approaches
Given a linked list containing N nodes and a positive integer K where K should be less than or equal to N. The task is to print the last K nodes of the list in reverse order. Examples: Input : list: 1-&gt;2-&gt;3-&gt;4-&gt;5, K = 2 Output : 5 4 Input : list: 3-&gt;10-&gt;6-&gt;9-&gt;12-&gt;2-&gt;8, K = 4 Output : 8 2 12 9 The solution discussed in
15+ min read
Append the last M nodes to the beginning of the given linked list.
Given a linked list and an integer M, the task is to append the last M nodes of the linked list to the front.Examples: Input: List = 4 -&gt; 5 -&gt; 6 -&gt; 1 -&gt; 2 -&gt; 3 -&gt; NULL, M = 3 Output: 1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; 5 -&gt; 6 -&gt; NULLInput: List = 8 -&gt; 7 -&gt; 0 -&gt; 4 -&gt; 1 -&gt; NULL, M = 2 Output: 4 -&gt; 1 -&gt; 8 -&gt;
13 min read
Find the sum of last n nodes of the given Linked List
Given a linked list and a number n. Find the sum of the last n nodes of the linked list.Constraints: 0 &lt;= n &lt;= number of nodes in the linked list. Examples: Input : 10-&gt;6-&gt;8-&gt;4-&gt;12, n = 2 Output : 16 Sum of last two nodes: 12 + 4 = 16 Input : 15-&gt;7-&gt;9-&gt;5-&gt;16-&gt;14, n = 4 Output : 44Recommended ProblemFind the Sum of L
15+ min read
Javascript Program To Find The Sum Of Last N Nodes Of The Given Linked List
Given a linked list and a number n. Find the sum of the last n nodes of the linked list.Constraints: 0 &lt;= n &lt;= number of nodes in the linked list. Examples: Input : 10-&gt;6-&gt;8-&gt;4-&gt;12, n = 2 Output : 16 Sum of last two nodes: 12 + 4 = 16 Input : 15-&gt;7-&gt;9-&gt;5-&gt;16-&gt;14, n = 4 Output : 44Method 1: (Recursive approach using
10 min read
Rearrange a linked list in to alternate first and last element
Given a linked list. arrange the linked list in manner of alternate first and last element. Examples: Input : 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6-&gt;7-&gt;8 Output :1-&gt;8-&gt;2-&gt;7-&gt;3-&gt;6-&gt;4-&gt;5 Input :10-&gt;11-&gt;15-&gt;13 Output :10-&gt;13-&gt;11-&gt;15 We have discussed three different solution in Rearrange a given linked list in-pl
8 min read
Swap first odd and even valued nodes from the beginning and end of a Linked List
Given a singly Linked List, the task is to swap the first odd valued node from the beginning and the first even valued node from the end of the Linked List. If the list contains node values of a single parity, then no modifications are required. Examples: Input: 4 -&gt; 3 -&gt; 5 -&gt; 2 -&gt; 3 -&gt; NULLOutput: 4 -&gt; 2 -&gt; 5 -&gt; 3 -&gt; 3 -
13 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
Append odd position nodes in reverse at the end of even positioned nodes in a Linked List
Given a linked list. The task is to segregate its even and odd position nodes in such a way that odd position nodes appear before even positioned nodes all the even positioned nodes must be in reverse order. Examples: Input: 1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; 5 -&gt; 6 -&gt; NULL Output : 1 -&gt; 3 -&gt; 5 -&gt; 6 -&gt; 4 -&gt; 2 -&gt; NULL Input : 1
11 min read
Javascript Program To Delete N Nodes After M Nodes Of A Linked List
Given a linked list and two integers M and N. Traverse the linked list such that you retain M nodes then delete next N nodes, continue the same till end of the linked list. Difficulty Level: Rookie Examples: Input:M = 2, N = 2Linked List: 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6-&gt;7-&gt;8Output:Linked List: 1-&gt;2-&gt;5-&gt;6Input:M = 3, N = 2Linked List
3 min read
Delete N nodes after M nodes of a linked list
Given a linked list and two integers m and n, the task is to traverse the linked list such that you skip m nodes, then delete the next n nodes, and continue the same till end of the linked list. Note: m cannot be 0. Example: Input: Linked List: 9-&gt;1-&gt;3-&gt;5-&gt;9-&gt;4-&gt;10-&gt;1, n = 1, m = 2 Output: 9-&gt;1-&gt;5-&gt;9-&gt;10-&gt;1 Expla
10 min read