Skip to main content

Insertion at end of circular doubly linked list in node js

Js program for Insertion at end of circular doubly linked list. Here problem description and other solutions.

// Node JS Program 
// Insert node at end of circular doubly linked list

// Define class of linked list Node
class LinkNode
{
	constructor(data)
	{
		// Set node value
		this.data = data;
		this.next = null;
		this.prev = null;
	}
}
class CircularDLL
{
	constructor()
	{
		this.head = null;
		this.tail = null;
	}
	// Insert node at end of circular doubly linked list
	insert(value)
	{
		// Create a node
		var node = new LinkNode(value);
		if (this.head == null)
		{
			// First node of linked list
			this.head = node;
			this.tail = node;
			node.next = node;
			node.prev = node;
		}
		else
		{
			node.next = this.head;
			node.prev = this.tail;
			this.head.prev = node;
			this.tail.next = node;
			// Set new last node
			this.tail = node;
		}
	}
	headToTail()
	{
		if (this.head == null)
		{
			console.log("Empty linked list");
		}
		else
		{
			var temp = this.head;
			console.log("\nNode Form Front to Rear :");
			while (temp != null)
			{
				process.stdout.write("  " + temp.data);
				temp = temp.next;
				if (temp == this.head)
				{
					return;
				}
			}
		}
	}
	tailToHead()
	{
		if (this.tail == null)
		{
			process.stdout.write("Empty linked list");
		}
		else
		{
			var temp = this.tail;
			console.log("\nNode Form Rear to Front :");
			while (temp != null)
			{
				process.stdout.write("  " + temp.data);;
				temp = temp.prev;
				if (temp == this.tail)
				{
					return;
				}
			}
		}
	}
}

function main()
{
	var cdll = new CircularDLL();
	// Add following linked list nodes
	cdll.insert(1);
	cdll.insert(2);
	cdll.insert(3);
	cdll.insert(4);
	cdll.insert(5);
	cdll.insert(6);
	// Display node
	cdll.headToTail();
	cdll.tailToHead();
}
// Start program execution
main();

Output

Node Form Front to Rear :
  1  2  3  4  5  6
Node Form Rear to Front :
  6  5  4  3  2  1




Comment

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