876. Middle of the Linked List LeetCode Solution

In this guide, you will get 876. Middle of the Linked List LeetCode Solution with the best time and space complexity. The solution to Middle of the Linked List problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Middle of the Linked List solution in C++
  4. Middle of the Linked List solution in Java
  5. Middle of the Linked List solution in Python
  6. Additional Resources
876. Middle of the Linked List LeetCode Solution image

Problem Statement of Middle of the Linked List

Given the head of a singly linked list, return the middle node of the linked list.
If there are two middle nodes, return the second middle node.

Example 1:

Input: head = [1,2,3,4,5]
Output: [3,4,5]
Explanation: The middle node of the list is node 3.

Example 2:

Input: head = [1,2,3,4,5,6]
Output: [4,5,6]
Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.

Constraints:

The number of nodes in the list is in the range [1, 100].
1 <= Node.val <= 100

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(1)

876. Middle of the Linked List LeetCode Solution in C++

class Solution {
 public:
  ListNode* middleNode(ListNode* head) {
    ListNode* slow = head;
    ListNode* fast = head;

    while (fast != nullptr && fast->next != nullptr) {
      slow = slow->next;
      fast = fast->next->next;
    }

    return slow;
  }
};
/* code provided by PROGIEZ */

876. Middle of the Linked List LeetCode Solution in Java

class Solution {
  public ListNode middleNode(ListNode head) {
    ListNode slow = head;
    ListNode fast = head;

    while (fast != null && fast.next != null) {
      slow = slow.next;
      fast = fast.next.next;
    }

    return slow;
  }
}
// code provided by PROGIEZ

876. Middle of the Linked List LeetCode Solution in Python

class Solution:
  def middleNode(self, head: ListNode) -> ListNode:
    slow = head
    fast = head

    while fast and fast.next:
      slow = slow.next
      fast = fast.next.next

    return slow
# code by PROGIEZ

Additional Resources

See also  193. Valid Phone Numbers LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.