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
pull/378/head
Akash Negi 2021-07-04 08:56:40 +05:30 committed by GitHub
parent a082e6a494
commit 572328394c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 47 additions and 32 deletions

View File

@ -1,39 +1,54 @@
//Description : Creating Circular linked list
#include <iostream> #include <iostream>
using namespace std; using namespace std;
struct Node { struct Node {
   int data; int data;
   struct Node *next; Node * next;
Node(int x) {
data = x;
next = NULL;
}
}; };
struct Node* head = NULL; Node * insertion(int newdata, Node * head) { //Insertion at the end of linked list
void insert(int newdata) { Node * newnode = new Node(newdata); //Creating a new node with value newdata
   struct Node *newnode = (struct Node *)malloc(sizeof(struct Node)); Node * ptr = head;
   struct Node *ptr = head; if (head == NULL) { //If the list was initially empty then return the newnode as the new head
   newnode->data = newdata; newnode -> next = newnode;
   newnode->next = head; return newnode;
   if (head!= NULL) {
      while (ptr->next != head)
      ptr = ptr->next;
      ptr->next = newnode;
   } else
   newnode->next = newnode;
   head = newnode;
} }
void display() { while (ptr -> next != head) { //Traversing till we reach the last node
   struct Node* ptr; ptr = ptr -> next;
   ptr = head;
   do {
      cout<<ptr->data <<" ";
      ptr = ptr->next;
   } while(ptr != head);
} }
int main() { newnode -> next = ptr -> next; //Insert the new node at the end of the list
   insert(3); ptr -> next = newnode;
   insert(1); return head;
   insert(7);
  insert(3); }
   insert(1);
   insert(7); void display(Node * head) { //Function to print items in the list
   cout<<"The circular linked list is: "; Node * ptr = head;
   display(); if (head == NULL) {
   return 0; cout << "Empty Circular Linked List";
return;
}
do {
cout << ptr -> data << " ";
ptr = ptr -> next;
}
while (ptr != head);
}
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;
} }