I need a detailed algorithm , in c# about how to find the middle element in linked List. I had checked google and all are talking about the two pointers which moves in parallel over the list . but actually , i couldn't find a detailed solution for the algorithm . and how these two pointers should be implemented .
i need the best solution regarding the performance .
This is pretty much what
juharr
suggested you in the comment for singly-linked list.GetMiddle
starts at head of the list,rightPointer
looks two elements ahead,leftPointer
looks at the next element (both pointers move in the same direction). In the end, when there are no more elements to examine,leftPointer
is the middle node of the list.In the code below
Node
is a singly-linked list node, andList
just adds elements to the list and exposes itshead
.In case of even number of elements, like
[1, 9]
the middle element is
5
.However, in case of even number of elements, line
[1, 10]
, algorithm will produce6
. That is because whenright
is at9
, it's next is notnull
but10
. So when we finish this iteration,right
is pointing tonull
andleft
is pointing at6
(which we return as middle).This means that in even case, you need to decide which element to take as middle - 5 or 6. If you want 5, you will need an extra condition in the loop:
The best solution to finding the middle element with respect to performance is to just compute it:
This returns the element after the middle when
list.Length
is even.If you want to return the element before the middle when
list.Length
is even, you can reduce and truncate:A Java solution for the above will be:
A Node here is: