Insert node at beginning of doubly linked list in c++

C++ program for Insert node at beginning of doubly linked list. Here problem description and other solutions.

// Include header file
#include <iostream>
using namespace std;
// C++ Program For
// insert new node at beginning of doubly linked list

// Define class of linked list Node
class LinkNode
{
	public: int data;
	LinkNode *next;
	LinkNode *prev;
	LinkNode(int data)
	{
		this->data = data;
		this->next = nullptr;
		this->prev = nullptr;
	}
};
class DoublyLinkedList
{
	public: LinkNode *head;
	DoublyLinkedList()
	{
		this->head = nullptr;
	}
	// Insert new node at beginning position
	void insert(int value)
	{
		// Create a node
		LinkNode *node = new LinkNode(value);
		node->next = this->head;
		// When linked list is not empty
		if (this->head != nullptr)
		{
			this->head->prev = node;
		}
		// Make new head
		this->head = node;
	}
	// Display node element of doubly linked list
	void display()
	{
		if (this->head == nullptr)
		{
			cout << "Empty Linked List" << endl;
		}
		else
		{
			cout << "  Doubly Linked List Element :" << endl;
			// Get first node of linked list
			LinkNode *temp = this->head;
			// iterate linked list 
			while (temp != nullptr)
			{
				// Display node value
				cout << "  " << temp->data;
				// Visit to next node
				temp = temp->next;
			}
		}
	}
};
int main()
{
	DoublyLinkedList *dll = new DoublyLinkedList();
	// Insert following linked list nodes
	dll->insert(70);
	dll->insert(60);
	dll->insert(50);
	dll->insert(40);
	dll->insert(30);
	dll->insert(20);
	dll->insert(10);
	//  NULL <- 10 <--> 20 <--> 30 <--> 40 <--> 50 <--> 60 <--> 70->NULL
	dll->display();
	return 0;
}

Output

  Doubly Linked List Element :
  10  20  30  40  50  60  70


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