Algo-Sim › Linked Lists
Middle of the Linked List
Easy · Linked Lists · step through it in Java, Python and C++ on your own input
Find the middle node in one pass: fast moves two steps for every one step of slow. Even lengths return the second middle.
Problem
Given the head of a singly linked list, return its middle node. When the list has an even number of nodes there are two middles; return the second one.
Constraints
- 1 ≤ number of nodes ≤ 100
- 1 ≤ Node.val ≤ 100
- Do it in one pass, without counting first
Edge cases to test
- One node
- Even length (second middle)
- Two nodes
Follow-up questions
- How do you get the first middle on even lengths?
- Start fast one node ahead (
fast = head.next), or stop whenfast.next.nextis null. - What is this used for?
- Splitting a list for merge sort, and finding the back half for the palindrome check and Reorder List.
Solution
Java
public ListNode middleNode(ListNode head) {
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}Python
def middle_node(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slowC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
ListNode *middleNode(ListNode *head) {
ListNode *slow = head, *fast = head;
while (fast != nullptr && fast->next != nullptr) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
};
More Linked Lists problems
- Reverse Linked List (Easy)
- Reverse Linked List (Recursive) (Easy)
- Merge Two Sorted Lists (Easy)
- Palindrome Linked List (Easy)
- Linked List Cycle (Easy)
- Linked List Cycle II (Medium)
- Intersection of Two Linked Lists (Easy)
- Find the Duplicate Number (Medium)
- Remove Nth Node From End of List (Medium)
- Reorder List (Medium)
- Sort List (Medium)
- Add Two Numbers (Medium)
- Copy List with Random Pointer (Medium)
- Reverse Nodes in k-Group (Hard)