0% found this document useful (0 votes)
3 views2 pages

Circular LinkedList Insertion

Uploaded by

chahmedk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views2 pages

Circular LinkedList Insertion

Uploaded by

chahmedk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

C++ Code for Insertion at the Beginning

#include <iostream>
using namespace std;

// Node structure
struct Node {
int data;
Node* next;
};

// Function to insert a new node at the beginning


void insertAtHead(Node*& head, int value) {
Node* newNode = new Node();
newNode->data = value;

// If the list is empty


if (head == nullptr) {
newNode->next = newNode; // Point to itself
head = newNode; // Update head
} else {
Node* temp = head;
while (temp->next != head) { // Find the last node
temp = temp->next;
}
temp->next = newNode; // Link last node to the new node
newNode->next = head; // New node points to head
head = newNode; // Update head to the new node
}
}

// Function to display the circular linked list


void display(Node* head) {
if (head == nullptr) {
cout << "List is empty!" << endl;
return;
}
Node* temp = head;
do {
cout << temp->data << " -> ";
temp = temp->next;
} while (temp != head);
cout << "(head)" << endl;
}

// Main function
int main() {
Node* head = nullptr; // Initialize head as null

// Insert nodes at the head


insertAtHead(head, 30);
insertAtHead(head, 20);
insertAtHead(head, 10);

// Display the circular linked list


cout << "Circular Linked List after insertions: ";
display(head);

return 0;
}

Explanation of the Code

1. Node Structure:
o A Node contains an integer data and a pointer to the next node.
2. Insert at Head Function:
o Creates a new node with the provided value.
o If the list is empty, it makes the new node point to itself and sets it as
the head.
o If the list is not empty, it traverses to find the last node and links it to
the new node, updating the new node to point to the head and finally
making it the new head.
3. Display Function:
o Traverses the list starting from the head, printing each node’s data
until it loops back to the head.
4. Main Function:
o Initializes the list and performs a series of insertions at the head.
o Finally, it displays the contents of the circular linked list.

You might also like