15 Aug 2020 - Hadron DaVinci
Find Middle Node of Double Linked List:
1 <=> 2 <=> 3 <=> 4 <=> 5 <=> 6
Truths:
step1:
Obtain the length of linked list by iterating from left side to right side once
while counting the number of nodes.
- Let length_linked_list = number of nodes
step2:
Find the mid point.
- Let mid_point = length_linked_list/2
step3:
Iterate through the list until we get to the middle
- Let current_node_index = 0, as code iterates, do current_node_index += 1
Stop when current_node_index >= mid_point
Since it’s a double linked list, we can iterate from both the left and right side.
step1:
Iterate from left side and right side at the same time.
step2:
When both iterators are on the same node, then it would be in the middle.
How would the code tell when the two are on the same node, you may ask?
Simply by comparing something unique about each node which may be either
the pointer, the node itself, the memory address that the node occupies in ram, etc.