insert node at beginning of circular linked list in c++

C++ program for insert node at beginning of circular linked list. Here problem description and explanation.

// Include header file
#include <iostream>
using namespace std;
// C++ Program 
// Insert node at beginning of circular linked list

// Define class of linked list Node
class LinkNode
{
	public: int data;
	LinkNode *next;
	LinkNode(int data, LinkNode *first)
	{
		this->data = data;
		this->next = first;
	}
};
class CircularLinkedList
{
	public: LinkNode *head;
	// Class constructors
	CircularLinkedList()
	{
		this->head = nullptr;
	}
	// Insert node at begining of circular linked list
	void insert(int value)
	{
		// Create a node
		LinkNode *node = new LinkNode(value, this->head);
		if (this->head == nullptr)
		{
			// First node of linked list
			this->head = node;
			node->next = this->head;
		}
		else
		{
			LinkNode *temp = this->head;
			// Find the last node
			while (temp->next != this->head)
			{
				// Visit to next node
				temp = temp->next;
			}
			// Add node
			temp->next = node;
			// make new head node
			this->head = node;
		}
	}
	// Display node element of circular linked list
	void display()
	{
		if (this->head == nullptr)
		{
			cout << "Empty Linked List" << endl;
		}
		else
		{
			cout << "  Linked List Element : " << endl;
			// Get first node
			LinkNode *temp = this->head;
			// iterate linked list
			while (temp != nullptr)
			{
				// Display node
				cout << "  " << temp->data;
				// Visit to next node
				temp = temp->next;
				if (temp == this->head)
				{
					// Stop iteration
					return;
				}
			}
		}
	}
};
int main()
{
	CircularLinkedList *task = new CircularLinkedList();
	// Add following linked list nodes
	task->insert(8);
	task->insert(7);
	task->insert(6);
	task->insert(5);
	task->insert(4);
	task->insert(3);
	task->insert(2);
	task->insert(1);
	// Display node
	task->display();
	return 0;
}

Output

  Linked List Element :
  1  2  3  4  5  6  7  8


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved