vault backup: 2026-03-05 12:28:58
This commit is contained in:
@@ -49,113 +49,7 @@ LeetCode 2. Medium
|
||||
|
||||
---
|
||||
|
||||
## Go 解法
|
||||
|
||||
```go
|
||||
/**
|
||||
* Definition for singly-linked list.
|
||||
* type ListNode struct {
|
||||
* Val int
|
||||
* Next *ListNode
|
||||
* }
|
||||
*/
|
||||
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
|
||||
// 哑节点,简化边界处理
|
||||
dummy := &ListNode{Val: 0}
|
||||
current := dummy
|
||||
carry := 0
|
||||
|
||||
// 同时遍历两个链表
|
||||
for l1 != nil || l2 != nil {
|
||||
// 获取当前位的值(如果链表已结束则为0)
|
||||
x, y := 0, 0
|
||||
if l1 != nil {
|
||||
x = l1.Val
|
||||
l1 = l1.Next
|
||||
}
|
||||
if l2 != nil {
|
||||
y = l2.Val
|
||||
l2 = l2.Next
|
||||
}
|
||||
|
||||
// 计算和与进位
|
||||
sum := x + y + carry
|
||||
carry = sum / 10
|
||||
|
||||
// 创建新节点
|
||||
current.Next = &ListNode{Val: sum % 10}
|
||||
current = current.Next
|
||||
}
|
||||
|
||||
// 处理最后的进位
|
||||
if carry > 0 {
|
||||
current.Next = &ListNode{Val: carry}
|
||||
}
|
||||
|
||||
return dummy.Next
|
||||
}
|
||||
```
|
||||
|
||||
### Go 代码要点
|
||||
1. 使用哑节点简化头节点处理
|
||||
2. 注意 Go 的 nil 判断
|
||||
3. 整数除法和取模:`sum / 10` 和 `sum % 10`
|
||||
|
||||
---
|
||||
|
||||
## Java 解法
|
||||
|
||||
```java
|
||||
/**
|
||||
* 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 addTwoNumbers(ListNode l1, ListNode l2) {
|
||||
// 哑节点
|
||||
ListNode dummy = new ListNode(0);
|
||||
ListNode current = dummy;
|
||||
int carry = 0;
|
||||
|
||||
// 同时遍历两个链表
|
||||
while (l1 != null || l2 != null) {
|
||||
// 获取当前位的值
|
||||
int x = (l1 != null) ? l1.val : 0;
|
||||
int y = (l2 != null) ? l2.val : 0;
|
||||
|
||||
// 计算和与进位
|
||||
int sum = x + y + carry;
|
||||
carry = sum / 10;
|
||||
|
||||
// 创建新节点
|
||||
current.next = new ListNode(sum % 10);
|
||||
current = current.next;
|
||||
|
||||
// 移动指针
|
||||
if (l1 != null) l1 = l1.next;
|
||||
if (l2 != null) l2 = l2.next;
|
||||
}
|
||||
|
||||
// 处理最后的进位
|
||||
if (carry > 0) {
|
||||
current.next = new ListNode(carry);
|
||||
}
|
||||
|
||||
return dummy.next;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Java 代码要点
|
||||
1. 三元运算符处理空指针
|
||||
2. 对象引用操作(current.next)
|
||||
3. 注意 null 判断
|
||||
## 解法
|
||||
|
||||
---
|
||||
|
||||
|
||||
Reference in New Issue
Block a user