給定一個鏈結串列,合併非零區間的節點(以加總的方式合併),輸出合併後的鏈結串列。
Example 1:
Input: head = [0,3,1,0,4,5,2,0]
Output: [4,11]
Explanation:
The above figure represents the given linked list. The modified list contains
- The sum of the nodes marked in green: 3 + 1 = 4.
- The sum of the nodes marked in red: 4 + 5 + 2 = 11.
Example 2:
Input: head = [0,1,0,3,0,2,2,0]
Output: [1,3,4]
Explanation:
The above figure represents the given linked list. The modified list contains
- The sum of the nodes marked in green: 1 = 1.
- The sum of the nodes marked in red: 3 = 3.
- The sum of the nodes marked in yellow: 2 + 2 = 4.
Constraints:
[3, 2 * 10^5]
.節點總數目介於3~二十萬之間。
0 <= Node.val <= 1000
節點值都介於0~1000 之間。
Node.val == 0
.不會有兩個相鄰的zero nodes
Node.val == 0
.第一個節點 和 最後一個節點保證是0
如果現在這個節點的節點值非零,就持續累加節點值,直到遇到zero node為止。
如果現在這個節點的節點值為零,則把加總的值更新到前一個節點prev上,接著啟動下一次的合併流程,直到遇到整條串列的尾端為止。
class Solution:
def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:
def merge(prev, cur, val):
if cur.val == 0:
# Merge nodes between 0s
prev.val = val
if cur.next is None:
# Tail node
prev.next = None
else:
# Non-tail node
prev.next = cur
merge(cur, cur.next, 0)
else:
# Keep accumulate value of node
merge(prev, cur.next, val+cur.val)
#---------------------------------
merge(head, head.next, 0)
return head
從頭到尾,每個節點拜訪一次,並且在過程中合併非零節點。
從頭到尾,每個節點拜訪一次,並且在過程中合併非零節點。
DFS call stack深度最深為O(n)