Leetcode Problem 2181. Merge Nodes in Between Zeros

2181. Merge Nodes in Between Zeros

Leetcode Solutions

Iterative In-Place Linked List Summation

  1. Initialize a dummy node (dummy) and set dummy.next to the head of the list.
  2. Initialize two pointers: curr to the first node and lastNonZero to dummy.
  3. Initialize a variable sum to 0.
  4. Iterate through the list until curr is not null. a. If curr.val is not zero, add curr.val to sum. b. If curr.val is zero, set lastNonZero.next.val to sum, link lastNonZero.next to curr, update lastNonZero to curr, and reset sum to 0.
  5. Move curr to the next node.
  6. Return dummy.next as the new head of the modified list.
UML Thumbnail

Accumulate and Reconstruct Linked List

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...