Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Find a middle element in a link list without traversing the entire list?

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?

like image 573
RAM Avatar asked May 08 '13 17:05

RAM


People also ask

How will you find the middle element of a singly linked list without iterating the list more than once in Python?

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.

How can you reach middle node in a linked list without knowing the number of nodes?

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.

How do you find the middle element of a singly linked list in one pass in Java?

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.


1 Answers

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.

like image 144
Jean-Bernard Pellerin Avatar answered Oct 15 '22 10:10

Jean-Bernard Pellerin