The reason why our slow pointer will be pointing to the middle of the linked list when our fast pointer is at end is that, as our slow pointer is travelling with half the speed of fast pointer so when the fast pointer will reach the end of the linked list, till that time slow pointer should have only travelled half the distance as travelled by fast pointer and hence it will be at the middle of the linked list.ĭo you know what the above-explained method is called? With the help of this technique, we can reach the middle node of a linked list in a single pass and hence our objective of finding the middle of linked list in one traversal will be achieved.If we notice carefully, by doing the above step, when the fast will reach the end of the list, the slow will be pointing to the middle of the list.Now, what will happen if we make the slow jump one place and the fast jump two places (fast moving with twice the speed of slow).What if we start by taking two pointers, say slow and fast, and make both of them point to the head initially.The middle of the list will be 15.Įxplanation: The middle of the given list is 15.Īs stated in the problem statement, we have to find the middle of the list in a single traversal. Suppose the given list is 5 → 10 → 15 → 4 → 8. 2 nd traversal to reach the (length/2) th node of the list which is actually the middle node of the linked list.īut here we have to find the middle of the linked list in one traversal.1 st traversal to find the length of the list.Usually, whenever we find the middle of a linked list, 2 traversals are needed. Problem Statement Understanding for Python program for middle element of linked list We have to find the middle of the linked list in a single traversal. In this problem, we are given a singly linked list. Lets just try to understand a Python program for middle element of linked list Problem Statement on how to find middle element of linked list in python We have different kinds of operations such as insertion, deletion and searching, let’s just look into one of the searches which is for middle element. We can define a linked list as a sequence of elements which are basically connected through links. Python program for middle element of linked list, how to find middle element of linked list in python.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |