Python program to find middle of a linked list using one traversal
Given a singly linked list, find the middle of the linked list. Given a singly linked list, find the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the output should be 3.
Method 1: Traverse the whole linked list and count the no. of nodes. Now traverse the list again till count/2 and return the node at count/2.
Method 2: Traverse linked list using two pointers. Move one pointer by one and another pointer by two. When the fast pointer reaches the end slow pointer will reach middle of the linked list.
The middle element is: 2
Method 3: Initialized the temp variable as head Initialized count to Zero Take loop till head will become Null(i.e end of the list) and increment the temp node when count is odd only, in this way temp will traverse till mid element and head will traverse all linked list. Print the data of temp.
- Time complexity: O(N) where N is the size of the given linked list
- Auxiliary Space: O(1) because it is using constant space