Program to find the middle node of a linked list




















Notice the code,. Here, we have two variables ptr1 and ptr2. We use these variables to iterate through the linked list. In each iteration, the ptr1 will access the two nodes and the ptr2 will access the single node of the linked list. Now, when the ptr1 reaches the end of the linked list, the ptr2 will be in the middle.

In this way, we are able to get the middle of linked list in a single iteration. In the above example, we have used the LinkedList class to implement the linked list data structure. Notice the expression,.

Course Index Explore Programiz. Java for Loop. Arrays in Java. Interfaces in Java. Java ArrayList. Popular Examples Check prime number. Move the slow pointer by one step and the fast pointer by two steps.

Proceeding this way, when the fast pointer will reach the end of the Linked List, the slow pointer will be at the middle of the Linked List. Clearly, we see that if the fast pointer cannot make a move or fast.

It is clear from the above illustration that in the case of an even number of nodes in the linked list, the middle node will be reached once the fast pointer points to null, and in case of an odd number of nodes in the linked list, the middle node will be reached once the fast pointer points to the last node. The list is iterated once, so the time complexity of the above method is O N , where N is the length of the Linked List.

If you are lucky enough that your interviewer allows you to use the Linked List class of collection framework , then finding the middle of the linked list becomes quite straightforward.

While most interviewers prefer to ask for direct implementation, some interviewers might also ask specifically for the above approach so as to test the knowledge of the Collection Framework in Java.

To find the middle element of a linked list, there are two possible approaches: 1. Iterate the list of elements once and count the number of nodes in the list. Use two pointer approach as discussed above. The time complexity of both the approaches as discussed above is O N where N is the size of the linked list.

This article discussed various approaches to find the middle node of a linked list. With this done you can now practice more questions related to the Linked List approach on Codestudio. If you are new to programming and want to learn more about programming languages, do check out the guided path available for free and amazing courses offered by Coding Ninjas.

About Us. Privacy Policy. Bug Bounty. Press Release. Write head. Push head, i ; ll. Previous Program for n'th node from the end of a Linked List. Next Write a function that counts the number of times a given int occurs in a Linked List. Recommended Articles. Article Contributed By :. Easy Normal Medium Hard Expert.

Writing code in comment? Please use ide. Load Comments.



0コメント

  • 1000 / 1000