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
Category: Data Structure And Algorithms | Tags: C# |
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
Answers:
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.
Lets run above code:
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.
Output
Middle node of given linked list is: 3