715242. Modify Linked List-1

Medium

Modify Linked List-1

Summary

This problem involves modifying a linked list by adding new nodes, removing existing nodes, or rearranging the order of nodes. The specific requirements and constraints will be explained in detail below.

Detailed Explanation

The given linked list needs to be modified according to certain conditions. We can start by identifying the specific operations that need to be performed on the linked list.

Let's assume we have a singly linked list head where each node has an integer value. The modification required is to remove all occurrences of a given target integer from the linked list.

Here are the steps to solve this problem:

  1. Initialize three pointers: curr, prev, and temp. Set curr to the head of the linked list, and set prev to null.
  2. Iterate through the linked list until curr points to null. In each iteration:
    • Check if the value at the current node is equal to the target integer.
    • If it is, move temp to the next node (temp = curr.next) and remove the current node from the list by changing prev.next to temp.
    • Move curr to the next node (curr = curr.next) and update prev accordingly.
  3. Once all nodes have been processed, return the modified head of the linked list.

Time complexity: O(n), where n is the number of nodes in the linked list. This is because we are processing each node once. Space complexity: O(1), as we are only using a constant amount of space to store our pointers.

Optimized Solutions

Java

View on GeeksforGeeks
public ListNode modifyList(ListNode head, int target) {
    ListNode curr = head;
    while (curr != null) {
        if (curr.val == target) {
            head = curr.next;
            curr = curr.next;
        } else {
            curr = curr.next;
        }
    }
    return head;
}

DevExCode

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

© 2026 DevExCode. All rights reserved.