How can I find a middle element in a linked list by traversing the entire list only once?
The length of the list is not given, and I am allowed to only use two pointers. How can this be done?
Move one pointer by one and other pointer by two. When the fast pointer reaches end slow pointer will reach 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. If there are even nodes, then there would be two middle nodes, we need to print the second middle element.
Approach 4: Using one pointer First, we will find the total size of the linked list. Then, we divide the total size by 2, and then whatever number comes, we move the pointer, starting from the head node, to that number of times. The node at which the pointer is pointing is the middle node of the linked list.
I don't see how you could do it without traversing the entire list unless you know the length.
I'm guessing the answer wants one pointer to be traversing one element at a time, while the second pointer moves 2 elements at a time.
This way when the second pointer reaches the end, the first pointer will be at the middle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With