Skip to content

1474. Delete N Nodes After M Nodes of a Linked List 👍

  • Time: $O(|\texttt{head}|)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
 public:
  ListNode* deleteNodes(ListNode* head, int m, int n) {
    ListNode* curr = head;
    ListNode* prev = nullptr;  // prev.next == curr

    while (curr != nullptr) {
      // Set the m-th node as `prev`.
      for (int i = 0; i < m & curr != nullptr; ++i) {
        prev = curr;
        curr = curr->next;
      }
      // Set the (m + n + 1)-th node as `curr`.
      for (int i = 0; i < n && curr != nullptr; ++i)
        curr = curr->next;
      // Delete the nodes [m + 1..n - 1].
      prev->next = curr;
    }

    return head;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
  public ListNode deleteNodes(ListNode head, int m, int n) {
    ListNode curr = head;
    ListNode prev = null; // prev.next == curr

    while (curr != null) {
      // Set the m-th node as `prev`.
      for (int i = 0; i < m & curr != null; ++i) {
        prev = curr;
        curr = curr.next;
      }
      // Set the (m + n + 1)-th node as `curr`.
      for (int i = 0; i < n && curr != null; ++i)
        curr = curr.next;
      // Delete the nodes [m + 1..n - 1].
      prev.next = curr;
    }

    return head;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution:
  def deleteNodes(
      self,
      head: ListNode | None,
      m: int,
      n: int,
  ) -> ListNode | None:
    curr = head
    prev = None  # prev.next == curr

    while curr:
      # Set the m-th node as `prev`.
      for _ in range(m):
        if not curr:
          break
        prev = curr
        curr = curr.next
      # Set the (m + n + 1)-th node as `curr`.
      for _ in range(n):
        if not curr:
          break
        curr = curr.next
      # Delete the nodes [m + 1..n - 1].
      prev.next = curr

    return head