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 lists are:Â
2 3 4Â
5 6 7 8ÂInput: 2 -> 4 -> 6 -> 8- > 10 -> 12, N = 4Â
Output:Â
Original list:Â
2 4 6 8 10 12Â
The new lists are:Â
2 4 6 8Â
10 12Â
Approach:Â Â
- Traverse an iterator until the required node i.e. the Kth node.
- Point the node just previous to the Kth node to the head of the original list.
- Point the last node of the original list to the Kth node.
Below is the implementation of the above approach:Â Â
C++
// C++ implementation of the approach#include<bits/stdc++.h>using namespace std;Â
class CircularLinkedList{    public:    struct Node     {        int data;        Node* next;    };Â
    Node* last;         // Function to add a node to the empty list    Node* addToEmpty(int data)    {        // If not empty        if (last != NULL)            return last;Â
        // Creating a node dynamically        Node *temp = new Node();Â
        // Assigning the data        temp->data = data;        last = temp;Â
        // Creating the link        last->next = last;Â
        return last;    }Â
    // Function to add a node to the    // beginning of the list    Node* addBegin(int data)    {Â
        // If list is empty        if (last == NULL)            return addToEmpty(data);Â
        // Create node        Node *temp = new Node();Â
        // Assign data        temp->data = data;        temp->next = last->next;        last->next = temp;Â
        return last;    }Â
    // Function to traverse and print the list    void traverse()    {        Node* p;Â
        // If list is empty        if (last == NULL)        {            cout<<("List is empty.");            return;        }Â
        // Pointing to the first Node of the list        p = last->next;Â
        // Traversing the list        do        {            cout << p->data << " ";            p = p->next;        } while (p != last->next);        cout << endl;    }Â
    // Function to find the length of the CircularLinkedList    int length()    {        // Stores the length        int x = 0;Â
        // List is empty        if (last == NULL)            return x;Â
        // Iterator Node to traverse the List        Node* itr = last->next;        while (itr->next != last->next)         {            x++;            itr = itr->next;        }Â
        // Return the length of the list        return (x + 1);    }Â
    // Function to split the first k nodes into    // a new CircularLinkedList and the remaining    // nodes stay in the original CircularLinkedList    Node* split(int k)    {Â
        // Empty Node for reference        Node* pass = new Node();Â
        // Check if the list is empty        // If yes, then return NULL        if (last == NULL)            return last;Â
        // NewLast will contain the last node of        // the new split list        // itr to iterate the node till        // the required node        Node* newLast, *itr = last;        for (int i = 0; i < k; i++)         {            itr = itr->next;        }Â
        // Update NewLast to the required node and        // link the last to the start of rest of the list        newLast = itr;        pass->next = itr->next;        newLast->next = last->next;        last->next = pass->next;Â
        // Return the last node of the required list        return newLast;    }};    // Driver codeint main(){    CircularLinkedList* clist = new CircularLinkedList();    clist->last = NULL;Â
    clist->addToEmpty(12);    clist->addBegin(10);    clist->addBegin(8);    clist->addBegin(6);    clist->addBegin(4);    clist->addBegin(2);    cout<<("Original list:");    clist->traverse();Â
    int k = 4;Â
    // Create a new list for the starting k nodes    CircularLinkedList* clist2 = new CircularLinkedList();Â
    // Append the new last node into the new list    clist2->last = clist->split(k);Â
    // Print the new lists    cout<<("The new lists are:");    clist2->traverse();    clist->traverse();}Â
// This code is contributed by Arnab Kundu |
Java
// Java implementation of the approachpublic class CircularLinkedList {Â
    Node last;Â
    static class Node {        int data;        Node next;    };Â
    // Function to add a node to the empty list    public Node addToEmpty(int data)    {        // If not empty        if (this.last != null)            return this.last;Â
        // Creating a node dynamically        Node temp = new Node();Â
        // Assigning the data        temp.data = data;        this.last = temp;Â
        // Creating the link        this.last.next = this.last;Â
        return last;    }Â
    // Function to add a node to the    // beginning of the list    public Node addBegin(int data)    {Â
        // If list is empty        if (last == null)            return addToEmpty(data);Â
        // Create node        Node temp = new Node();Â
        // Assign data        temp.data = data;        temp.next = this.last.next;        this.last.next = temp;Â
        return this.last;    }Â
    // Function to traverse and print the list    public void traverse()    {        Node p;Â
        // If list is empty        if (this.last == null) {            System.out.println("List is empty.");            return;        }Â
        // Pointing to the first Node of the list        p = this.last.next;Â
        // Traversing the list        do {            System.out.print(p.data + " ");            p = p.next;        } while (p != this.last.next);Â
        System.out.println("");    }Â
    // Function to find the length of the CircularLinkedList    public int length()    {        // Stores the length        int x = 0;Â
        // List is empty        if (this.last == null)            return x;Â
        // Iterator Node to traverse the List        Node itr = this.last.next;        while (itr.next != this.last.next) {            x++;            itr = itr.next;        }Â
        // Return the length of the list        return (x + 1);    }Â
    // Function to split the first k nodes into    // a new CircularLinkedList and the remaining    // nodes stay in the original CircularLinkedList    public Node split(int k)    {Â
        // Empty Node for reference        Node pass = new Node();Â
        // Check if the list is empty        // If yes, then return null        if (this.last == null)            return this.last;Â
        // NewLast will contain the last node of        // the new split list        // itr to iterate the node till        // the required node        Node newLast, itr = this.last;        for (int i = 0; i < k; i++) {            itr = itr.next;        }Â
        // Update NewLast to the required node and        // link the last to the start of rest of the list        newLast = itr;        pass.next = itr.next;        newLast.next = this.last.next;        this.last.next = pass.next;Â
        // Return the last node of the required list        return newLast;    }Â
    // Driver code    public static void main(String[] args)    {        CircularLinkedList clist = new CircularLinkedList();        clist.last = null;Â
        clist.addToEmpty(12);        clist.addBegin(10);        clist.addBegin(8);        clist.addBegin(6);        clist.addBegin(4);        clist.addBegin(2);        System.out.println("Original list:");        clist.traverse();Â
        int k = 4;Â
        // Create a new list for the starting k nodes        CircularLinkedList clist2 = new CircularLinkedList();Â
        // Append the new last node into the new list        clist2.last = clist.split(k);Â
        // Print the new lists        System.out.println("The new lists are:");        clist2.traverse();        clist.traverse();    }} |
Python3
# Python3 implementation of the approach Â
# Node of Linked Listclass Node:         def __init__(self, x):                 self.data = x        self.next = None         # Function to add a node to the empty listdef addToEmpty(last, data):         # If not empty    if (last != None):        return lastÂ
    # Assigning the data    temp = Node(data)    last = tempÂ
    # Creating the link    last.next = lastÂ
    return lastÂ
# Function to add a node to the# beginning of the listdef addBegin(last, data):         # If list is empty    if (last == None):        return addToEmpty(data)Â
    # Create node    temp = Node(data)Â
    temp.next = last.next    last.next = tempÂ
    return lastÂ
# Function to traverse and print listdef traverse(last):         # If list is empty    if (last == None):        print("List is empty.")        returnÂ
    # Pointing to the first Node of the list    p = last.nextÂ
    # Traversing the list    while True:        print(p.data, end = " ")        p = p.nextÂ
        if p == last.next:            break             print()Â
# Function to find the length of # the CircularLinkedListdef length(last):         # Stores the length    x = 0Â
    # List is empty    if (last == None):        return xÂ
    # Iterator Node to traverse the List    itr = last.next    while (itr.next != last.next):        x += 1        itr = itr.nextÂ
    # Return the length of the list    return (x + 1)Â
# Function to split the first k nodes into# a new CircularLinkedList and the remaining# nodes stay in the original CircularLinkedListdef split(last, k):Â
    # Empty Node for reference    passs = Node(-1)Â
    # Check if the list is empty    # If yes, then return NULL    if (last == None):        return lastÂ
    # NewLast will contain the last node of    # the new split list itr to iterate the    # node till the required node    itr = last    for i in range(k):        itr = itr.nextÂ
    # Update NewLast to the required node    # and link the last to the start of     # rest of the list    newLast = itr    passs.next = itr.next    newLast.next = last.next    last.next = passs.nextÂ
    # Return the last node of the     # required list    return newLastÂ
# Driver codeif __name__ == '__main__':Â Â Â Â Â Â Â Â Â clist = NoneÂ
    clist = addToEmpty(clist, 12)    clist = addBegin(clist, 10)    clist = addBegin(clist, 8)    clist = addBegin(clist, 6)    clist = addBegin(clist, 4)    clist = addBegin(clist, 2)         print("Original list:", end = "")    traverse(clist)Â
    k = 4Â
    # Append the new last node    # into the new list    clist2 = split(clist, k)Â
    # Print the new lists    print("The new lists are:", end = "")    traverse(clist2)    traverse(clist)Â
# This code is contributed by mohit kumar 29 |
C#
// C# implementation of the approachusing System;Â Â Â Â Â public class CircularLinkedList{Â
    public Node last;Â
    public class Node     {        public int data;        public Node next;    };Â
    // Function to add a node to the empty list    public Node addToEmpty(int data)    {        // If not empty        if (this.last != null)            return this.last;Â
        // Creating a node dynamically        Node temp = new Node();Â
        // Assigning the data        temp.data = data;        this.last = temp;Â
        // Creating the link        this.last.next = this.last;Â
        return last;    }Â
    // Function to add a node to the    // beginning of the list    public Node addBegin(int data)    {Â
        // If list is empty        if (last == null)            return addToEmpty(data);Â
        // Create node        Node temp = new Node();Â
        // Assign data        temp.data = data;        temp.next = this.last.next;        this.last.next = temp;Â
        return this.last;    }Â
    // Function to traverse and print the list    public void traverse()    {        Node p;Â
        // If list is empty        if (this.last == null)        {            Console.WriteLine("List is empty.");            return;        }Â
        // Pointing to the first Node of the list        p = this.last.next;Â
        // Traversing the list        do        {            Console.Write(p.data + " ");            p = p.next;        } while (p != this.last.next);Â
        Console.WriteLine("");    }Â
    // Function to find the length of the CircularLinkedList    public int length()    {        // Stores the length        int x = 0;Â
        // List is empty        if (this.last == null)            return x;Â
        // Iterator Node to traverse the List        Node itr = this.last.next;        while (itr.next != this.last.next)         {            x++;            itr = itr.next;        }Â
        // Return the length of the list        return (x + 1);    }Â
    // Function to split the first k nodes into    // a new CircularLinkedList and the remaining    // nodes stay in the original CircularLinkedList    public Node split(int k)    {Â
        // Empty Node for reference        Node pass = new Node();Â
        // Check if the list is empty        // If yes, then return null        if (this.last == null)            return this.last;Â
        // NewLast will contain the last node of        // the new split list        // itr to iterate the node till        // the required node        Node newLast, itr = this.last;        for (int i = 0; i < k; i++)         {            itr = itr.next;        }Â
        // Update NewLast to the required node and        // link the last to the start of rest of the list        newLast = itr;        pass.next = itr.next;        newLast.next = this.last.next;        this.last.next = pass.next;Â
        // Return the last node of the required list        return newLast;    }Â
    // Driver code    public static void Main(String[] args)    {        CircularLinkedList clist = new CircularLinkedList();        clist.last = null;Â
        clist.addToEmpty(12);        clist.addBegin(10);        clist.addBegin(8);        clist.addBegin(6);        clist.addBegin(4);        clist.addBegin(2);        Console.WriteLine("Original list:");        clist.traverse();Â
        int k = 4;Â
        // Create a new list for the starting k nodes        CircularLinkedList clist2 = new CircularLinkedList();Â
        // Append the new last node into the new list        clist2.last = clist.split(k);Â
        // Print the new lists        Console.WriteLine("The new lists are:");        clist2.traverse();        clist.traverse();    }}Â
// This code is contributed by Rajput-Ji |
Javascript
<script>// Javascript implementation of the approachÂ
class Node{Â Â Â Â constructor()Â Â Â Â {Â Â Â Â Â Â Â Â let data;Â Â Â Â Â Â Â Â let next;Â Â Â Â }}Â
// Function to add a node to the empty listfunction addToEmpty(last,data){    // If not empty        if (last != null)            return last;          // Creating a node dynamically        let temp = new Node();          // Assigning the data        temp.data = data;        last = temp;          // Creating the link        last.next = last;          return last;}Â
// Function to add a node to the    // beginning of the listfunction addBegin(last, data){    // If list is empty        if (last == null)            return addToEmpty(data);          // Create node        let temp = new Node();          // Assign data        temp.data = data;        temp.next = last.next;        last.next = temp;          return last;}Â
// Function to traverse and print the listfunction traverse(last){    let p;          // If list is empty        if (last == null) {            document.write("List is empty.<br>");            return;        }          // Pointing to the first Node of the list        p = last.next;          // Traversing the list        do {            document.write(p.data + " ");            p = p.next;        } while (p != last.next);          document.write("<br>");}Â
// Function to find the length of the CircularLinkedListfunction length(last){    // Stores the length        let x = 0;          // List is empty        if (last == null)            return x;          // Iterator Node to traverse the List        let itr = last.next;        while (itr.next != last.next) {            x++;            itr = itr.next;        }          // Return the length of the list        return (x + 1);}Â
// Function to split the first k nodes into    // a new CircularLinkedList and the remaining    // nodes stay in the original CircularLinkedListfunction split(last,k){    // Empty Node for reference        let pass = new Node();          // Check if the list is empty        // If yes, then return null        if (last == null)            return last;          // NewLast will contain the last node of        // the new split list        // itr to iterate the node till        // the required node        let newLast, itr = last;        for (let i = 0; i < k; i++) {            itr = itr.next;        }          // Update NewLast to the required node and        // link the last to the start of rest of the list        newLast = itr;        pass.next = itr.next;        newLast.next = last.next;        last.next = pass.next;          // Return the last node of the required list        return newLast;}Â
// Driver codelet clist = null;Â Â clist=addToEmpty(clist,12);clist=addBegin(clist,10);clist=addBegin(clist,8);clist=addBegin(clist,6);clist=addBegin(clist,4);clist=addBegin(clist,2);document.write("Original list:<br>");traverse(clist);Â
let k = 4;Â
Â
Â
// Append the new last node into the new listlet clist2 = split(clist, k)Â
// Print the new listsdocument.write("The new lists are:<br>");traverse(clist2);traverse(clist);Â
Â
Â
// This code is contributed by unknown2108</script> |
Output:Â
Original list: 2 4 6 8 10 12 The new lists are: 2 4 6 8 10 12
Â
Time Complexity: O(N)
Auxiliary Space: O(1)Â
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



