update leetcode

This commit is contained in:
2025-09-02 21:06:57 +08:00
parent 003eb24c77
commit c308ed1d64
20 changed files with 290 additions and 2 deletions

View File

@@ -0,0 +1,6 @@
[package]
name = "p2"
version = "0.1.0"
edition = "2024"
[dependencies]

View File

@@ -0,0 +1,101 @@
// Definition for singly-linked list.
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ListNode {
pub val: i32,
pub next: Option<Box<ListNode>>,
}
impl ListNode {
#[inline]
fn new(val: i32) -> Self {
ListNode { next: None, val }
}
}
fn add_two_numbers(l1: Option<Box<ListNode>>, l2: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
let mut dummy_head = Box::new(ListNode::new(0));
let mut current = &mut dummy_head;
let mut p1 = l1.as_ref();
let mut p2 = l2.as_ref();
let mut carry = 0;
while p1.is_some() || p2.is_some() || carry != 0 {
let val1 = p1.map_or(0, |node| node.val);
let val2 = p2.map_or(0, |node| node.val);
let sum = val1 + val2 + carry;
carry = sum / 10;
current.next = Some(Box::new(ListNode::new(sum % 10)));
current = current.next.as_mut().unwrap();
p1 = p1.and_then(|node| node.next.as_ref());
p2 = p2.and_then(|node| node.next.as_ref());
}
dummy_head.next
}
fn main() {
// 测试用例 1: 342 + 465 = 807
let l1 = Some(Box::new(ListNode {
val: 2,
next: Some(Box::new(ListNode {
val: 4,
next: Some(Box::new(ListNode { val: 3, next: None })),
})),
}));
let l2 = Some(Box::new(ListNode {
val: 5,
next: Some(Box::new(ListNode {
val: 6,
next: Some(Box::new(ListNode { val: 4, next: None })),
})),
}));
let result = add_two_numbers(l1, l2);
println!("Test 1: {:?}", result); // 期望: [7, 0, 8]
// 测试用例 2: 0 + 0 = 0
let l1 = Some(Box::new(ListNode::new(0)));
let l2 = Some(Box::new(ListNode::new(0)));
let result = add_two_numbers(l1, l2);
println!("Test 2: {:?}", result); // 期望: [0]
// 测试用例 3: 99 + 9 = 108 (有进位)
let l1 = Some(Box::new(ListNode {
val: 9,
next: Some(Box::new(ListNode { val: 9, next: None })),
}));
let l2 = Some(Box::new(ListNode::new(9)));
let result = add_two_numbers(l1, l2);
println!("Test 3: {:?}", result); // 期望: [8, 0, 1]
// 测试用例 4: 999 + 1 = 1000 (多位进位)
let l1 = Some(Box::new(ListNode {
val: 9,
next: Some(Box::new(ListNode {
val: 9,
next: Some(Box::new(ListNode { val: 9, next: None })),
})),
}));
let l2 = Some(Box::new(ListNode::new(1)));
let result = add_two_numbers(l1, l2);
println!("Test 4: {:?}", result); // 期望: [0, 0, 0, 1]
// 测试用例 5: 长度不同的链表 12 + 9999 = 10011
let l1 = Some(Box::new(ListNode {
val: 2,
next: Some(Box::new(ListNode { val: 1, next: None })),
}));
let l2 = Some(Box::new(ListNode {
val: 9,
next: Some(Box::new(ListNode {
val: 9,
next: Some(Box::new(ListNode {
val: 9,
next: Some(Box::new(ListNode { val: 9, next: None })),
})),
})),
}));
let result = add_two_numbers(l1, l2);
println!("Test 5: {:?}", result); // 期望: [1, 1, 0, 0, 1]
}