Find the middle element of linked list


Category: Data Structure And Algorithms Tags: C#

Write a program to find the middle element of linked list. Suppose linked list is as below:

Head -> 1 -> 2 -> 3 -> 4 -> 5

Output

Middle node of given linked list is: 3


Like 0 People
Asked on 14 June 2021
Nikhil Joshi

Nikhil Joshi
Ceo & Founder at Dotnetlovers
Atricles: 146
Questions: 16
Given Best Solutions: 16 *

Answers:

Nikhil Joshi

We can solve it using two pointers one is normal pointer increments one and other pointer is called fast pointer which jumps two elements in one iteration. So once fast pointer reaches the end it leaves normal pointer in mid.

static Node MidOfLinkedList(Node head)
{
    Node normalPointer = head;
    Node fastPointer = head;

    while (fastPointer != null && fastPointer.Next != null)
    {
        fastPointer = fastPointer.Next.Next;
        normalPointer = normalPointer.Next;
    }
    return normalPointer;
}

Let's run above code.

static void Main(string[] args)
{
    Node head = new Node(1);
    head.Next = new Node(2);
    head.Next.Next = new Node(3);
    head.Next.Next.Next = new Node(4);
    head.Next.Next.Next.Next = new Node(5);

    Node middleNode = MidOfLinkedList(head);

    Console.WriteLine($"Middle node of given linked list is: " + middleNode.Value);
}

Output

Middle node of given linked list is: 3

Like 0 People on 14 June 2021

You are not loggedin, please login or signup to add comments:

Existing User

Login via:

New User



x