LeetCode 1171. 从链表中删去总和值为零的连续节点

题目描述

🔥 1171. 从链表中删去总和值为零的连续节点

思路分析

前缀和

参考代码

1
write your code here

🍏 点击查看 Java 题解

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
27
28
29
30
31
public class Solution {
    public ListNode removeZeroSumSublists(ListNode head) {
        if (head == null) {
            return null;
        }

        // 使用 HashMap 存储累积和以及对应的节点
        Map<Integer, ListNode> map = new HashMap<>();
        int sum = 0;
        ListNode dummy = new ListNode();
        dummy.next = head;
        ListNode cur = dummy;

        while (cur != null) {
            sum += cur.val;
            map.put(sum, cur);
            cur = cur.next;
        }

        // 重新遍历链表,删除总和为 0 的子链表
        sum = 0;
        cur = dummy;
        while (cur != null) {
            sum += cur.val;
            cur.next = map.get(sum).next;
            cur = cur.next;
        }

        return dummy.next;
    }
}
本文作者:
本文链接: https://hgnulb.github.io/blog/47592196
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!