Find Middle Element of Linked List
From Given a singly linked list, write a program to find the middle element of Linked List.
For example
Input:
1->2->3
Output:
2
Solution:
using System;
namespace LinkedListOpearation
{
public class Program
{
public static void Main()
{
//creating LinkedList with 5 elements including head
LinkedList linkedList = new LinkedList();
Node head = linkedList.Head;
linkedList.Add(new Node("1"));
linkedList.Add(new Node("2"));
linkedList.Add(new Node("3"));
linkedList.Add(new Node("4"));
//finding middle element of LinkedList in single pass
Node current = head;
int length = 0;
Node middle = head;
while (current.Next != null)
{
length++;
if (length % 2 == 0)
{
middle = middle.Next;
}
current = current.Next;
}
if (length % 2 == 1)
{
middle = middle.Next;
}
Console.WriteLine($"LinkedList length:{length} ");
Console.WriteLine($"LinkedList middle element:{middle.Data}");
Console.ReadLine();
}
}
class LinkedList
{
public Node Tail { get; set; }
public Node Head { get; set; }
public LinkedList()
{
Head = new Node("head");
Tail = Head;
}
public void Add(Node node)
{
Tail.Next = node;
Tail = node;
}
}
public class Node
{
public Node Next { get; set; }
public string Data { get; set; }
public Node(string data)
{
Data = data;
}
}
}