Circular List is a list in which all nodes are connected to each other in the form of circle. i.e. last node connected to first node, first node connected to second node and so on..
there is no null at the end of Circular List.
Write a program to create a Singly Linked Circular List.
Solution:
using System;
namespace SinglyLinkedCircularList {
class CircularList {
private readonly int _currentNode;
private CircularList _nextNode;
static void Main() {
var node1 = new CircularList(1);
node1.DeleteNode();
var node2 = node1.InsertNode(2);
node1.DeleteNode();
node2 = node1.InsertNode(2);
var node3 = node2.InsertNode(3);
var node4 = node3.InsertNode(4);
var node5 = node4.InsertNode(5);
node1.GetNodes();
node3.GetNodes();
node5.GetNodes();
node1.Traverse();
node3.DeleteNode();
node2.Traverse();
node1.GetNodes();
node3.GetNodes();
node5.GetNodes();
Console.ReadLine();
}
public CircularList(int value) {
_currentNode = value;
_nextNode = this;
}
public CircularList InsertNode(int value) {
var node = new CircularList(value);
if (_nextNode == this) {
node._nextNode = this;
_nextNode = node;
} else {
var temp = _nextNode;
node._nextNode = temp;
_nextNode = node;
}
return node;
}
public void DeleteNode() {
if (_nextNode == this) {
Console.WriteLine("Single node");
return;
}
_nextNode = _nextNode._nextNode;
}
public void Traverse() {
Traverse(this);
}
public void Traverse(CircularList node) {
if (node == null) node = this;
Console.WriteLine("Forward Direction");
var singleNode = node;
do {
Console.WriteLine(node._currentNode);
node = node._nextNode;
} while (node != singleNode);
}
public int GetNodes() {
return GetNodes(this);
}
public int GetNodes(CircularList node) {
if (node == null) node = this;
var count = 0;
var singleNode = node;
do {
count++;
node = node._nextNode;
} while (node != singleNode);
Console.WriteLine("Current Node Value : " + node._currentNode);
Console.WriteLine("Total nodes :" + count);
return count;
}
}
}