快慢指针同时向后遍历,快指针记录sum值,最后返回的结点值由慢指针保存。 为了能够在最后修改链表的尾巴,所以追踪的是快慢指针的next
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeNodes(ListNode* head) {
ListNode *slow = head, *fast = head;
while(fast->next != nullptr){
int sum = 0;
while(fast->next != nullptr && fast->next->val == 0){ //快指针快速向后移动
fast = fast->next;
}
while(fast->next != nullptr && fast->next->val != 0){
sum += fast->next->val;
fast = fast->next;
}
if(sum != 0){
slow->next->val = sum;
slow = slow->next;
}
}
slow->next = nullptr;
return head->next;
}
};
时间复杂度:
空间复杂度:
错误写法,这种写法虽然追踪了当前指针,但是无法修改最后一个结点的尾巴。
class Solution {
public:
ListNode* mergeNodes(ListNode* head) {
ListNode *slow = head, *fast = head;
while(fast != nullptr){
int sum = 0;
while(fast != nullptr && fast->val == 0){ //快指针快速向后移动
fast = fast->next;
}
while(fast != nullptr && fast->val != 0){
sum += fast->val;
fast = fast->next;
}
if(sum != 0){
slow->val = sum;
slow = slow->next;
}
}
slow = nullptr;
return head;
}
};