1. Convert Singly Linked List to circular linked list.
2. Check the number of nodes in Circular Linked List
3. Check if the given list is a circular linked list.
1. Convert Singly Linked List to circular linked list
To do this, we need to traverse at the end of the list and assign the next of the last node to the head of the list
2. Check the number of nodes in Circular Linked List
To do this, we take a temp node, and start counting the number of nodes till the temp node is not equal to the head node.
3. Check if the given list is a circular linked list.
To do this, we take a temp node and start traversing the list, till the temp node is not equal to head, or till the temp node is null in case of non circular LL.
Solution in C++
#include<iostream> #include<vector> #include<string> using namespace std; struct Node { int data; Node *next; Node(int x) { data = x; next = NULL; } }; void print_list(Node *head) { Node *start = head; while(start) { cout<<start->data<<" -> "; start = start->next; } cout<<"\n"; } void make_linked_list_circular(Node *head) { Node *start = head; while(head -> next != NULL) head = head -> next; head -> next = start; } void count_nodes_circular_linked_list(Node *head) { Node *temp = head -> next; int count = 1; while(temp != head) { count++; temp = temp -> next; } cout<<"\n\nThe total number of nodes in circular linked list is "<< count << endl; } void check_if_list_is_circular_linked_list(Node *head) { Node *temp = head -> next; while(temp != NULL && temp != head) temp = temp -> next; if (temp == head) cout<<"The list is circular linked list"<<endl; else cout<<"The list is not circular linked list"<<endl; } int main() { Node *head = new Node(2); head -> next = new Node(1); head -> next -> next = new Node(4); head -> next -> next -> next = new Node(3); head -> next -> next -> next -> next = new Node(6); head -> next -> next -> next -> next -> next = new Node(5); cout<<"The original list = "<<endl; print_list(head); cout<<"Check if the list is circular"<<endl;; check_if_list_is_circular_linked_list(head); make_linked_list_circular(head); cout<<"\n\nAfter making list as circular, check if the list is circular "<<endl; check_if_list_is_circular_linked_list(head); count_nodes_circular_linked_list(head); return 0; }
Output:
The original list = 2 -> 1 -> 4 -> 3 -> 6 -> 5 -> Check if the list is circular The list is not circular linked list After making list as circular, check if the list is circular The list is circular linked list The total number of nodes in circular linked list is 6