# How to find mid of a linked list

 Category: Data Structure And Algorithms Tags:

Write a program to find mid element from a given 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
 Nikhil Joshi Ceo & Founder at Dotnetlovers Atricles: 164 Questions: 16 Given Best Solutions: 16 *

1. Using two pointers

We can have two pointers normal moving and fast moving pointer(moves twice as much as normal pointer). Once fast moving pointer reaches end, normal moving pointer ends up in mid and that is out answer.

```static Node MidOfLinkedListUsingTwoPointers(Node head)
{

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

Lets run above code:

```static void Main(string[] args)
{

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

Output

Middle node of given linked list is: 3

2. Counting length of linked list

We can first count the length of linked list by iterating it till end and then iterate it next time until the half of the count.

```static Node MidOfLinkedListUsingLenght(Node head)
{
int count = 0;

while (temp != null)
{
temp = temp.Next;
count++;
}

var mid = count / 2;

while (mid > 0)
{
temp = temp.Next;
mid--;
}
return temp;
}```
```static void Main(string[] args)
{

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

Output

Middle node of given linked list is: 3

Like 0 People on 20 June 2021