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>
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<<ptr->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;
}