One of the algo for this would be:
- Traverse the list and find the length of list
- After finding length, again traverse the list and locate n/2 element from head of linkedlist.
  Time complexity=time for finding length of list + time for locating
  middle element=o(n)+o(n) =o(n)
Space
  complexity= o(1).
Efficient approach:
Above approach will take two traversal but we can find middle element in one traversal also using following algo
Use two pointer fastptr and slowptr and initialize both to head of linkedlist
- Move fastptr by two nodes and slowptr by one node in each iteration.
- When fastptr reaches end of nodes, the slowptr pointer will be pointing to middle element.
Lets create java program for it:
Logically linked list can be represented as:
  The middle element is represented in red color.
Run the above program, and you will get the following output:
Don't miss the next article! 
 Be the first to be notified when a new article or Kubernetes experiment is   published.                            
  
Share This

 
 
