Write a Program to find the maximum and minimum value node from a singly linked list
Solution:
using System;
namespace LinkedListOpearation
{
class Program
{
public static void Main()
{
var linkedList = new LinkedList();
linkedList.Add(6);
linkedList.Add(1);
linkedList.Add(5);
linkedList.Add(2);
linkedList.Add(3);
linkedList.Add(9);
Console.WriteLine("Sorted Linked List is:");
linkedList.Print(linkedList.Head);
Console.WriteLine($"Min node: {linkedList.MinNode()}");
Console.WriteLine($"Max node: {linkedList.MaxNode()}");
Console.ReadLine();
}
}
public class LinkedList
{
public Node Head;
public void Add(int data)
{
var node = new Node(data) {Next = Head};
Head = node;
}
public int MinNode()
{
var current = Head;
if (Head == null)
throw new Exception();
var min = Head.Data;
while (current != null)
{
if (min > current.Data)
min = current.Data;
current = current.Next;
}
return min;
}
public int MaxNode()
{
var current = Head;
if (Head == null)
throw new Exception();
var max = Head.Data;
while (current != null)
{
if (max < current.Data)
max = current.Data;
current = current.Next;
}
return max;
}
public void Print(Node head)
{
while (head != null)
{
Console.WriteLine(head.Data);
head = head.Next;
}
}
}
public class Node
{
public int Data;
public Node Next;
public Node(int data)
{
Data = data;
}
}
}