How to Find middle element in a linked list - The Coding Shala
Home >> Interview Prep >> Find the middle element in a linked list
Other Posts You May Like
In this post, we will learn how to find the middle element in a linked list and will implement its solution in Java.
Find a middle element in a linked list Problem
Given a singly linked list of N nodes. The task is to find the middle of the linked list.
Example 1:
Input:
LinkedList: 1->2->3->4->5
Output: 3
Explanation:
Middle of linked list is 3.
Example 2:
Input:
LinkedList: 2->4->6->7->5->1
Output: 7
Explanation:
Middle of linked list is 7.
Find a middle element in a linked list Java Solution
Approach 1
You can find the total length of the linked list then traverse again from starting and return the middle element.
A better approach is to take two pointers one is a slow pointer, move by one step, and one fast pointer, move by two steps. At the time the fast pointer reaches the end slow is at the middle node.
Java Program:
/* Node of a linked list class Node { int data; Node next; Node(int d) { data = d; next = null; } } */ class Solution { int getMiddle(Node head) { Node slow = head; Node fast = head; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } return slow.data; } }
- Detect Cycle in a Linked List
- Find First Node of a Cycle in a Linked List
- The Intersection of Two Linked Lists
- Remove Nth Node from the end of a Linked List
- Reverse a Linked List
Comments
Post a Comment