700665. Insert in Middle of Linked List

Basic

Insert in Middle of Linked List

Slug: insert-in-middle-of-linked-list

Difficulty: Basic

Id: 700665

Topic Tags: Linked List, Data Structures

Company Tags: None

Summary

The problem is to insert a new node into the middle of a linked list. The key concepts involved are basic data structures and algorithms, particularly linked lists.

Detailed Explanation

To solve this problem, we will first need to find the middle of the linked list. We can do this by iterating through the list until we reach the halfway point. Once we have found the middle, we can insert our new node into the list at that position.

Here is a step-by-step breakdown of the solution:

  1. Initialize two pointers, slow and fast, to the beginning of the linked list.
  2. Iterate through the list until fast reaches the end of the list. For each iteration:
    • Move slow one node forward.
    • Move fast two nodes forward (if there is an odd number of nodes, this will still point to the correct position).
  3. Once fast has reached the end of the list, slow will be pointing to the middle node. Insert our new node after slow.

Optimized Solutions

Java

View on GeeksforGeeks
public class Solution {
    public void insertInMiddle(Node head, int data) {
        if (head == null || head.next == null) {
            return; // list has only one or zero nodes
        }

        Node slow = head;
        Node fast = head;

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

        Node newNode = new Node(data);
        newNode.next = slow.next;
        slow.next = newNode;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.