Insertion at end of circular doubly linked list in c#
Csharp program for Insertion at end of circular doubly linked list. Here problem description and other solutions.
// Include namespace system
using System;
// Csharp Program
// Insert node at end of circular doubly linked list
// Define class of linked list Node
public class LinkNode
{
public int data;
public LinkNode next;
public LinkNode prev;
public LinkNode(int data)
{
// Set node value
this.data = data;
this.next = null;
this.prev = null;
}
}
public class CircularDLL
{
public LinkNode head;
public LinkNode tail;
public CircularDLL()
{
// Set head and tail values
this.head = null;
this.tail = null;
}
// Insert node at end of circular doubly linked list
public void insert(int 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;
}
}
public void headToTail()
{
if (this.head == null)
{
Console.WriteLine("Empty linked list");
}
else
{
var temp = this.head;
Console.WriteLine("\nNode Form Front to Rear :");
while (temp != null)
{
Console.Write(temp.data + " ");
temp = temp.next;
if (temp == this.head)
{
return;
}
}
}
}
public void tailToHead()
{
if (this.tail == null)
{
Console.Write("Empty linked list");
}
else
{
var temp = this.tail;
Console.WriteLine("\nNode Form Rear to Front :");
while (temp != null)
{
Console.Write(temp.data + " ");
temp = temp.prev;
if (temp == this.tail)
{
return;
}
}
}
}
public static void Main(String[] args)
{
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();
}
}
Output
Node Form Front to Rear :
1 2 3 4 5 6
Node Form Rear to Front :
6 5 4 3 2 1
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