⭐️ 题目描述
🌟 leetcode链接:从链表中删去总和值为零的连续节点
思路:
在链表的 head
前新增加一个哨兵卫的头结点,方便计算前缀和。遍历链表,依次把每个节点的 val
相加到 sum
中去,再判断 sum = 0
依次删除这段区间的节点,要画图注意边界,以及迭代的条件即可。
代码:
struct ListNode* removeZeroSumSublists(struct ListNode* head){
// 在链表前面加一个哨兵卫结点
struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
newNode->next = head;
struct ListNode* cur = newNode;
while (cur != NULL) {
int sum = 0;
struct ListNode* curNext = cur->next;
// 前缀和
while (curNext != NULL) {
sum += curNext->val;
// 当 sum = 0 时
if (sum == 0) {
// 释放 [cur->next , curNext]
struct ListNode* temp = cur->next;
while (temp != curNext) {
struct ListNode* next = temp->next;
free(temp);
temp = next;
}
cur->next = curNext->next;
curNext = cur;
free(temp);
}
curNext = curNext->next;
}
cur = cur->next;
}
head = newNode->next;
free(newNode);
return head;
}