From 572328394c89bde100c99ad8d90828bce5c7aecb Mon Sep 17 00:00:00 2001 From: Akash Negi <55234838+NegiAkash890@users.noreply.github.com> Date: Sun, 4 Jul 2021 08:56:40 +0530 Subject: [PATCH] enh(CPlusPlus): circular linked lists (#353) * Code Refactor This refactors the previous code to make it more readable and user friendly * Fixed bug and added useful comments * Fixed Typo --- .../CPlusPlus/Linked-Lists/circular.cpp | 79 +++++++++++-------- 1 file changed, 47 insertions(+), 32 deletions(-) diff --git a/algorithms/CPlusPlus/Linked-Lists/circular.cpp b/algorithms/CPlusPlus/Linked-Lists/circular.cpp index 0cf9aaf4..6488cfc2 100644 --- a/algorithms/CPlusPlus/Linked-Lists/circular.cpp +++ b/algorithms/CPlusPlus/Linked-Lists/circular.cpp @@ -1,39 +1,54 @@ +//Description : Creating Circular linked list + #include using namespace std; + struct Node { -   int data; -   struct Node *next; + int data; + Node * next; + Node(int x) { + data = x; + next = NULL; + } }; -struct Node* head = NULL; -void insert(int newdata) { -   struct Node *newnode = (struct Node *)malloc(sizeof(struct Node)); -   struct Node *ptr = head; -   newnode->data = newdata; -   newnode->next = head; -   if (head!= NULL) { -      while (ptr->next != head) -      ptr = ptr->next; -      ptr->next = newnode; -   } else -   newnode->next = newnode; -   head = newnode; +Node * insertion(int newdata, Node * head) { //Insertion at the end of linked list + Node * newnode = new Node(newdata); //Creating a new node with value newdata + Node * ptr = head; + if (head == NULL) { //If the list was initially empty then return the newnode as the new head + newnode -> next = newnode; + return newnode; + } + while (ptr -> next != head) { //Traversing till we reach the last node + ptr = ptr -> next; + } + newnode -> next = ptr -> next; //Insert the new node at the end of the list + ptr -> next = newnode; + return head; + } -void display() { -   struct Node* ptr; -   ptr = head; -   do { -      cout<data <<" "; -      ptr = ptr->next; -   } while(ptr != head); + +void display(Node * head) { //Function to print items in the list + Node * ptr = head; + if (head == NULL) { + cout << "Empty Circular Linked List"; + return; + } + do { + cout << ptr -> data << " "; + ptr = ptr -> next; + } + while (ptr != head); } -int main() { -   insert(3); -   insert(1); -   insert(7); -  insert(3); -   insert(1); -   insert(7); -   cout<<"The circular linked list is: "; -   display(); -   return 0; + +int main() { //Main Driver function + Node * head = NULL; + head = insertion(3, head); + head = insertion(4, head); + head = insertion(5, head); + head = insertion(6, head); + head = insertion(1, head); + head = insertion(7, head); + display(head); + return 0; + }