Smallest and largest element in circular linked list in c#
Csharp program for Smallest and largest element in circular linked list. Here problem description and explanation.
// Include namespace system
using System;
// Csharp Program for
// Find the minimum and maximum nodes in circular linked list
// Define class of linked list Node
public class LinkNode
{
public int data;
public LinkNode next;
public LinkNode(int data, LinkNode first)
{
this.data = data;
this.next = first;
}
}
public class CircularLinkedList
{
public LinkNode head;
// Class constructor
public CircularLinkedList()
{
this.head = null;
}
// Insert node at end of circular linked list
public void insert(int value)
{
// Create a new node
var node = new LinkNode(value, this.head);
if (this.head == null)
{
// First node of linked list
this.head = node;
node.next = this.head;
}
else
{
var temp = this.head;
// Find the last node
while (temp.next != this.head)
{
// Visit to next node
temp = temp.next;
}
// Add new node at the last
temp.next = node;
}
}
// Find the min max nodes
public void findMinAndMax()
{
if (this.head == null)
{
Console.WriteLine("Empty linked list");
return;
}
// Auxiliary variables
var temp = this.head.next;
var min = this.head;
var max = this.head;
while (temp != null && temp != this.head)
{
if (min.data > temp.data)
{
// Get min node value
min = temp;
}
if (max.data < temp.data)
{
// Get max node value
max = temp;
}
// Visit to next node
temp = temp.next;
}
// Display calculated result
Console.WriteLine(" Min : " + min.data);
Console.WriteLine(" Max : " + max.data);
}
public static void Main(String[] args)
{
var cll = new CircularLinkedList();
// Insert element of linked list
cll.insert(31);
cll.insert(15);
cll.insert(59);
cll.insert(45);
cll.insert(14);
cll.insert(58);
cll.insert(49);
cll.insert(57);
cll.findMinAndMax();
}
}
Output
Min : 14
Max : 59
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