The Wayback Machine - https://web.archive.org/web/20240927183232/https://www.geeksforgeeks.org/convert-singly-linked-list-circular-linked-list/
Open In App

Convert singly linked list into circular linked list

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

Given a singly linked list, the task is to convert it into a circular linked list.

Examples:

Input: head: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL
Output:

Traversal-of-Circular-Linked-List


Explanation: Singly linked list is converted to circular by pointing last node to head.


Input: head: 2 -> 4 -> 6 -> 8 -> 10 -> 12 -> NULL
Output:

Traversal-of-Circular-Linked-List-2


Explanation: Singly linked list is converted to circular by pointing last node to head.

[Expected Approach – 1] Using Recursion – O(n) Time and O(n) Space:

To convert a singly linked list into a circular linked list using recursion, begin by recursively traversing the list to reach the last node, which is the node whose next pointer is nullptr. Update last node’s next pointer to point back to the head node to form a circular link.

Below is the implementation of the above approach:

C++
// C++ Program for converting singly linked list
// into circular linked list.
#include <bits/stdc++.h>
using namespace std;

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

// Function that convert singly linked list
// into circular linked list.
void circular(Node *curr, Node *head) {

    // if last node, then point next ptr
    // to head Node
    if (curr->next == nullptr) {
        curr->next = head;
        return;
    }

    // otherwise traverse to the
    // next node
    circular(curr->next, head);
}

void printList(Node *head) {
    Node *curr = head;

    do {
        cout << curr->data << " ";
        curr = curr->next;

    } while (curr != head);
    cout << endl;
}

int main() {

    // create a hard coded list
    // 10->12->14->16
    Node *head = new Node(10);
    head->next = new Node(12);
    head->next->next = new Node(14);
    head->next->next->next = new Node(16);

    circular(head, head);

    printList(head);

    return 0;
}
C
// C Program for converting singly linked list
// into circular linked list.
#include <stdio.h>
#include <stdlib.h>

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

// Function that converts singly linked list into 
// circular linked list
void circular(struct Node* curr, struct Node* head) {
    
    // if last node, then point next ptr
    // to head Node
    if (curr->next == NULL) {
        curr->next = head;
        return;
    }
    
    // otherwise traverse to the 
    // next node
    circular(curr->next, head);
}

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

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

int main() {
    
    // create a hard coded list 10->12->14->16
    struct Node* head = createNode(10);
    head->next = createNode(12);
    head->next->next = createNode(14);
    head->next->next->next = createNode(16);
    
    circular(head, head);
    
    printList(head);
    
    return 0;
}
Java
// Java Program for converting singly linked list
// into circular linked list.

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

public class GfG {
    
    // Function that converts singly linked 
      // list into circular linked list
    static void circular(Node curr, Node head) {
        
        // if last node, then point next ptr
        // to head Node
        if (curr.next == null) {
            curr.next = head;
            return;
        }
        
        // otherwise move to the 
        // next node
        circular(curr.next, head);
    }
    
    static void printList(Node head) {
        Node curr = head;
        
        do {
            System.out.print(curr.data + " ");
            curr = curr.next;
        } while (curr != head);
        System.out.println();
    }

    public static void main(String[] args) {
        
        // create a hard coded list 10->12->14->16
        Node head = new Node(10);
        head.next = new Node(12);
        head.next.next = new Node(14);
        head.next.next.next = new Node(16);
        
        circular(head, head);
        
        printList(head);
    }
}
Python
# Python program for converting singly linked list
# into circular linked list.
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

# Function that converts singly linked list 
# into circular linked list
def circular(curr, head):
    
    # if last node, then point next ptr
    # to head Node
    if curr.next == None:
        curr.next = head
        return
    
    # otherwise move to the 
    # next node
    circular(curr.next, head)

def printList(head):
    curr = head
    
    while True:
        print(curr.data, end=" ")
        curr = curr.next
        if curr == head:
            break
    print()

if __name__ == "__main__":
    
    # create a hard coded list 10->12->14->16
    head = Node(10)
    head.next = Node(12)
    head.next.next = Node(14)
    head.next.next.next = Node(16)
    
    circular(head, head)
    
    printList(head)
C#
// C# Program for converting singly linked list
// into circular linked list.
using System;

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

class GfG {
    
    // Function that converts singly linked list 
    // into circular linked list
    static void Circular(Node curr, Node head) {
        
        // if last node, then point next ptr
        // to head Node
        if (curr.next == null) {
            curr.next = head;
            return;
        }
        
        // otherwise move to the 
        // next node
        Circular(curr.next, head);
    }
    
    static void PrintList(Node head) {
        Node curr = head;
        
        do {
            Console.Write(curr.data + " ");
            curr = curr.next;
        } while (curr != head);
        Console.WriteLine();
    }

    static void Main(string[] args) {
        
        // create a hard coded list 10->12->14->16
        Node head = new Node(10);
        head.next = new Node(12);
        head.next.next = new Node(14);
        head.next.next.next = new Node(16);
        
        Circular(head, head);
        
        PrintList(head);
    }
}
JavaScript
// Javascript program for converting singly linked list
// into circular linked list.
class Node {
    constructor(data) {
        this.data = data;
        this.next = null;
    }
}

// Function that converts singly linked 
// list into circular linked list
function circular(curr, head) {
    
    // if last node, then point next ptr
    // to head Node
    if (curr.next == null) {
        curr.next = head;
        return;
    }
    
    // otherwise move to the 
    // next node
    circular(curr.next, head);
}

function printList(head) {
    let curr = head;
    
    do {
        console.log(curr.data + " ");
        curr = curr.next;
    } while (curr !== head);
}

// create a hard coded list
// 10->12->14->16
let head = new Node(10);
head.next = new Node(12);
head.next.next = new Node(14);
head.next.next.next = new Node(16);

circular(head, head);

printList(head);

Output
10 12 14 16 

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

[Expected Approach – 2] Using Iterative Approach – O(n) Time and O(1) Space:

To convert a singly linked list into a circular linked list iteratively, start by initializing a pointer to traverse the list from the head node. Traverse the list until we reach the node whose next pointer that is nullptr. Update its next pointer to point back to the head node.

Below is the implementation of the above approach:

C++
// C++ Program for converting singly linked list
// into circular linked list.
#include <bits/stdc++.h>
using namespace std;

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

// Function that convert singly linked list
// into circular linked list.
Node *circular(Node *head) {

    // declare a node variable curr and
    // assign head node into curr node.
    Node *curr = head;

    // check that while curr->next is not equal
    // to NULL then curr points to next node.
    while (curr->next != nullptr)
        curr = curr->next;

    // assign curr->next to the head node.
    curr->next = head;

    return head;
}

void printList(Node *head) {
    Node *curr = head;

    do {
        cout << curr->data << " ";
        curr = curr->next;

    } while (curr != head);
    cout << endl;
}

int main() {

    // create a hard coded list
    // 10->12->14->16
    Node *head = new Node(10);
    head->next = new Node(12);
    head->next->next = new Node(14);
    head->next->next->next = new Node(16);

    head = circular(head);

    printList(head);

    return 0;
}
C
// C Program for converting singly linked list
// into circular linked list.
#include <stdio.h>
#include <stdlib.h>

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

// Function that converts singly linked list into 
// circular linked list
struct Node* circular(struct Node* head) {
    
    // declare a node variable curr and 
    // assign head node into curr node.
    struct Node* curr = head;
    
    // check that while curr->next is not equal
    // to NULL then curr points to next node.
    while (curr->next != NULL)
        curr = curr->next;
    
    // assign curr->next to the head node.
    curr->next = head;
    return head;
}

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

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

int main() {
    
    // create a hard coded list 10->12->14->16
    struct Node* head = createNode(10);
    head->next = createNode(12);
    head->next->next = createNode(14);
    head->next->next->next = createNode(16);
    
    head = circular(head);
    
    printList(head);
    
    return 0;
}
Java
// Java Program for converting singly linked list
// into circular linked list.
class Node {
    int data;
    Node next;
    
    Node(int data) {
        this.data = data;
        this.next = null;
    }
}

public class GfG {
    
    // Function that converts singly linked 
      // list into circular linked list
    static Node circular(Node head) {
        
        // declare a node variable curr and 
        // assign head node into curr node.
        Node curr = head;
        
        // check that while curr->next is not equal
        // to NULL then curr points to next node.
        while (curr.next != null)
            curr = curr.next;
        
        // assign curr->next to the head node.
        curr.next = head;
        return head;
    }
    
    static void printList(Node head) {
        Node curr = head;
        
        do {
            System.out.print(curr.data + " ");
            curr = curr.next;
        } while (curr != head);
        System.out.println();
    }

    public static void main(String[] args) {
        
        // create a hard coded list 10->12->14->16
        Node head = new Node(10);
        head.next = new Node(12);
        head.next.next = new Node(14);
        head.next.next.next = new Node(16);
        
        head = circular(head);
        
        printList(head);
    }
}
Python
# Python program for converting singly linked list
# into circular linked list.
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

# Function that converts singly linked list 
# into circular linked list
def circular(head):
    
    # declare a node variable curr and 
    # assign head node into curr node.
    curr = head
    
    # check that while curr->next is not equal
    # to NULL then curr points to next node.
    while curr.next is not None:
        curr = curr.next
    
    # assign curr->next to the head node.
    curr.next = head
    
    return head

def printList(head):
    curr = head
    
    while True:
        print(curr.data, end=" ")
        curr = curr.next
        if curr == head:
            break
    print()

if __name__ == "__main__":
    
    # create a hard coded list 10->12->14->16
    head = Node(10)
    head.next = Node(12)
    head.next.next = Node(14)
    head.next.next.next = Node(16)
    
    head = circular(head)
    
    printList(head)
C#
// C# Program for converting singly linked list
// into circular linked list.
using System;

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

class GfG {
    
    // Function that converts singly linked list 
    // into circular linked list
    static Node Circular(Node head) {
        
        // declare a node variable curr and 
        // assign head node into curr node.
        Node curr = head;
        
        // check that while curr->next is not equal
        // to NULL then curr points to next node.
        while (curr.next != null)
            curr = curr.next;
        
        // assign curr->next to the head node.
        curr.next = head;
        
        return head;
    }
    
    static void PrintList(Node head) {
        Node curr = head;
        
        do {
            Console.Write(curr.data + " ");
            curr = curr.next;
        } while (curr != head);
        Console.WriteLine();
    }

    static void Main(string[] args) {
        
        // create a hard coded list 10->12->14->16
        Node head = new Node(10);
        head.next = new Node(12);
        head.next.next = new Node(14);
        head.next.next.next = new Node(16);
        
        head = Circular(head);
        
        PrintList(head);
    }
}
JavaScript
// Javascript program for converting singly linked list
// into circular linked list.
class Node {
    constructor(data) {
        this.data = data;
        this.next = null;
    }
}

// Function that converts singly linked 
// list into circular linked list
function circular(head) {
    
    // declare a node variable curr and 
    // assign head node into curr node.
    let curr = head;
    
    // check that while curr->next is not equal
    // to NULL then curr points to next node.
    while (curr.next !== null) {
        curr = curr.next;
    }
    
    // assign curr->next to the head node.
    curr.next = head;
    
    return head;
}

function printList(head) {
    let curr = head;
    
    do {
        console.log(curr.data + " ");
        curr = curr.next;
    } while (curr !== head);
}

// create a hard coded list
// 10->12->14->16
let head = new Node(10);
head.next = new Node(12);
head.next.next = new Node(14);
head.next.next.next = new Node(16);

head = circular(head);

printList(head);

Output
10 12 14 16 

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



Similar Reads

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
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->11->32->6->13->20 Output : 9 32 6 20 Input : 6->11->16->21->17->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
Find minimum and maximum elements in singly Circular Linked List
Given a singly circular linked list of [Tex]N [/Tex]nodes. The task is to find the smallest and largest elements in the circular linked list. Examples: Input : List = 99->11->22->33->44->55->66 Output : Minimum = 11, Maximum = 99 Input : List = 12->11->9->33->125->6->99 Output : Minimum = 6, Maximum = 125 The ide
14 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->6->7->8->9->10->11->11 K = 11 Output : Sum = 22, Product = 121 Input : List = 15->7->3->9->11->5 K = 5 Output : Product = 75, Sum = 20 Approach: Initi
12 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 -> 11 -> 34 -> 6 -> 13 -> 20 Output: 9 -> 11 -> 6 -> 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 -> 11 -> 34 -> 6 -> 13 -> 21 Output: 9 -> 34 -> 21 Explanation: The circular singly linked list contains : 9 -> 9 11 -> 1 + 1 = 2 34 -> 3 +
12 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 -> 11 -> 34 -> 6 -> 13 -> 21 Output: 11 -> 13 -> 21 Explanation: The circular singly linked list contains : 11 -> 1011, parity
15+ min read
Insertion in Circular Singly Linked List
In this article, we will learn how to insert a node to a circular linked list. In a circular linked list, the last node connects back to the first node, creating a loop. There are four main ways to add items: Insertion in an empty listInsertion at the beginning of the listInsertion at the end of the listInsertion at specific position in the listNow
15+ 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
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
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
Convert a String to a Singly Linked List
Given string str, the task is to convert it into a singly Linked List. Examples: Input: str = "ABCDABC" Output: A -> B -> C -> D -> A -> B -> C Input: str = "GEEKS" Output: G -> E -> E -> K -> S Approach: Create a Linked ListFetch each character of the string and insert it into a new node in the Linked ListPrint the Li
5 min read
Convert a Singly Linked List to an array
Given a singly linked list and the task is to convert it into an array. Examples: Input: List = 1 -> 2 -> 3 -> 4 -> NULL Output: 1 2 3 4 Input: List = 10 -> 20 -> 30 -> 40 -> 50 -> NULL Output: 10 20 30 40 50 Approach: The idea is to iterate through the linked list and for each node add its value into the array. [GFGTABS]
5 min read
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 < K < 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 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8, K = 3 Output: Original list: 2 3 4 5 6 7 8 The new li
13 min read
Split a Circular Linked List into three halves of almost same size
Split given Circular Linked List into three halves without calculating its length such that the difference between a linked list with a maximum number of nodes and a linked list with a minimum number of nodes is minimum. Examples: Input: Circular Linked List: 1->3->5->7->9Output: 1 3 5 7 9 Input: Circular Linked List: 2->4->8Outpu
10 min read
Split a Circular Linked List into two halves
Given a Circular linked list. The task is split into two Circular Linked lists. If there are an odd number of nodes in the given circular linked list then out of the resulting two halved lists, the first list should have one node more than the second list. Examples: Input: 10->4->9Output: 10->4 , 9Explanation: Number of nodes in circular L
10 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->4->6->7->5 Output: trueExplanation: As shown in figure the first a
12 min read
Convert an Array to a Circular Doubly Linked List
Prerequisite: Doubly Linked list, Circular Linked List, Circular Doubly Linked ListGiven an array of N elements. The task is to write a program to convert the array into a circular doubly linked list. The idea is to start traversing the array and for every array element create a new list node and assign the prev and next pointers of this node accor
8 min read
What is Circular Queue | Circular Queue meaning
A circular queue is an extended version of regular queue in which the last element of the queue is connected to the first element of the queue forming a cycle. Properties of Circular Queue: Along with the properties of a regular queue the circular queue has som other unique properties as mentioned below: Front and rear pointers: Two pointers, one a
4 min read
Select a Random Node from a Singly Linked List
Given a singly linked list, select a random node from the linked list (the probability of picking a node should be 1/N if there are N nodes in the list). You are given a random number generator.Below is a Simple Solution Count the number of nodes by traversing the list. Traverse the list again and select every node with a probability of 1/N. The se
15 min read
Alternate Odd and Even Nodes in a Singly Linked List
Given a singly linked list, rearrange the list so that even and odd nodes are alternate in the list.There are two possible forms of this rearrangement. If the first data is odd, then the second node must be even. The third node must be odd and so on. Notice that another arrangement is possible where the first node is even, second odd, third even an
15+ min read
Find middle of singly linked list Recursively
Given a singly linked list and the task is to find the middle of the linked list. Examples: Input : 1->2->3->4->5 Output : 3 Input : 1->2->3->4->5->6 Output : 4 We have already discussed Iterative Solution. In this post iterative solution is discussed. Count total number of nodes in the list in recursive manner and do hal
5 min read
C Program to reverse each node value in Singly Linked List
A linked list is a linear collection of data elements, in which each node points to the next node. Unlike an array, it doesn't have upper limit and hence extremely useful. The task is to access value of each node of linked list and reverse them. Examples: Input : 56 87 12 49 35 Output : 65 78 21 94 53 Input : 128 87 12433 491 33 Output : 821 78 334
2 min read
Delete all Prime Nodes from a Singly Linked List
Given a singly linked list containing N nodes, the task is to delete all nodes from the list which are prime.Examples: Input : List = 15 -> 16 -> 6 -> 7 -> 17 Output : Final List = 15 -> 16 -> 6Input : List = 15 -> 3 -> 4 -> 2 -> 9 Output :Final List = 15 ->4 -> 9 Approach: The idea is to traverse the nodes of th
12 min read
Sum of the nodes of a Singly Linked List
Given a singly linked list. The task is to find the sum of nodes of the given linked list. Examples: Input: 7->6->8->4->1 Output: 26 Sum of nodes: 7 + 6 + 8 + 4 + 1 = 26 Input: 1->7->3->9->11->5 Output: 36 Recursive Solution: Call a function by passing the head and variable to store the sum.Then recursively call the funct
12 min read
Sum and Product of the nodes of a Singly Linked List which are divisible by K
Given a singly linked list. The task is to find the sum and product of all of the nodes of the given linked list which are divisible by a given number k. Examples: Input : List = 7->60->8->40->1 k = 10 Output : Product = 2400, Sum = 100Product of nodes: 60 * 40 = 2400Input : List = 15->7->3->9->11->5 k = 5Output : Product
15 min read
Minimum and Maximum Prime Numbers of a Singly Linked List
Given a singly linked list containing N nodes, the task is to find the minimum and maximum prime number. Examples: Input : List = 15 -> 16 -> 6 -> 7 -> 17 Output : Minimum : 7 Maximum : 17 Input : List = 15 -> 3 -> 4 -> 2 -> 9 Output : Minimum : 2 Maximum : 3 Approach: The idea is to traverse the linked list to the end and i
9 min read
Update adjacent nodes if the current node is zero in a Singly Linked List
Given a linked list. The task is to change the value of the previous and next node of a node to 0 if the current node is 0. Examples: Input : 2->3->4->5->0->9->0->9->NULL Output : 2->3->4->0->0->0->0->0->NULL Input : 0->2->3->4->0->0->NULL Output : 0->0->3->0->0->0-
10 min read
Reverse alternate K nodes in a Singly Linked List - Iterative Solution
Given a linked list and an integer K, the task is to reverse every alternate K nodes.Examples: Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> NULL, K = 3 Output: 3 2 1 4 5 6 9 8 7Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> NULL, K = 5 Output: 5 4 3 2 1 6 7 8 9 Approach: We have alre
12 min read
Remove all special characters from a singly Linked List
Given a singly linked list where each node represents a character including special characters, the task is to remove all the occurrences of special characters from the linked list so that only valid characters are present in the linked list. Examples: Input: List = ( -> G -> E -> E -> * -> K -> S -> * -> NULL Output: G -
12 min read