上次编辑到这里,代码来自缓存 点击恢复默认模板
/**
* 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) {
}
};
cpp 解法, 执行用时: 495 ms, 内存消耗: 252 MB, 提交时间: 2024-09-09 09:06:14
/**
* 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) {
auto tail = head;
for (auto cur = head->next; cur->next; cur = cur->next) {
if (cur->val) {
tail->val += cur->val;
} else {
tail = tail->next;
tail->val = 0;
}
}
// 注:这里没有 delete 剩余节点,可以自行补充
tail->next = nullptr;
return head;
}
};
java 解法, 执行用时: 6 ms, 内存消耗: 78.1 MB, 提交时间: 2024-09-09 09:05:57
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeNodes(ListNode head) {
ListNode tail = head;
for (ListNode cur = head.next; cur.next != null; cur = cur.next) {
if (cur.val != 0) {
tail.val += cur.val;
} else {
tail = tail.next;
tail.val = 0;
}
}
tail.next = null;
return head;
}
}
javascript 解法, 执行用时: 418 ms, 内存消耗: 89.1 MB, 提交时间: 2024-09-09 09:05:36
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var mergeNodes = function(head) {
let tail = head;
for (let cur = head.next; cur.next; cur = cur.next) {
if (cur.val) {
tail.val += cur.val;
} else {
tail = tail.next;
tail.val = 0;
}
}
tail.next = null;
return head;
};
golang 解法, 执行用时: 280 ms, 内存消耗: 13.6 MB, 提交时间: 2022-11-10 17:39:28
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func mergeNodes(head *ListNode) *ListNode {
ans := head
for node, sum := head.Next, 0; node != nil; node = node.Next {
if node.Val != 0 {
sum += node.Val
} else {
ans.Next.Val = sum // 原地修改
ans = ans.Next
sum = 0
}
}
ans.Next = nil
return head.Next
}
python3 解法, 执行用时: 2108 ms, 内存消耗: 102.9 MB, 提交时间: 2022-11-10 17:32:24
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy = tail = ListNode()
total = 0
cur = head.next
while cur:
if cur.val == 0:
node = ListNode(total)
tail.next = node
tail = tail.next
total = 0
else:
total += cur.val
cur = cur.next
return dummy.next