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 Typopull/378/head
parent
a082e6a494
commit
572328394c
|
@ -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)
|
while (ptr -> next != head) { //Traversing till we reach the last node
|
||||||
ptr = ptr->next;
|
ptr = ptr -> next;
|
||||||
ptr->next = newnode;
|
}
|
||||||
} else
|
newnode -> next = ptr -> next; //Insert the new node at the end of the list
|
||||||
newnode->next = newnode;
|
ptr -> next = newnode;
|
||||||
head = newnode;
|
return head;
|
||||||
|
|
||||||
}
|
}
|
||||||
void display() {
|
|
||||||
struct Node* ptr;
|
void display(Node * head) { //Function to print items in the list
|
||||||
ptr = head;
|
Node * ptr = head;
|
||||||
do {
|
if (head == NULL) {
|
||||||
cout<<ptr->data <<" ";
|
cout << "Empty Circular Linked List";
|
||||||
ptr = ptr->next;
|
return;
|
||||||
} while(ptr != head);
|
}
|
||||||
|
do {
|
||||||
|
cout << ptr -> data << " ";
|
||||||
|
ptr = ptr -> next;
|
||||||
|
}
|
||||||
|
while (ptr != head);
|
||||||
}
|
}
|
||||||
int main() {
|
|
||||||
insert(3);
|
int main() { //Main Driver function
|
||||||
insert(1);
|
Node * head = NULL;
|
||||||
insert(7);
|
head = insertion(3, head);
|
||||||
insert(3);
|
head = insertion(4, head);
|
||||||
insert(1);
|
head = insertion(5, head);
|
||||||
insert(7);
|
head = insertion(6, head);
|
||||||
cout<<"The circular linked list is: ";
|
head = insertion(1, head);
|
||||||
display();
|
head = insertion(7, head);
|
||||||
return 0;
|
display(head);
|
||||||
|
return 0;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue