刷题第二天。今天下班其实很早,但是一晚上都在学rust的Option,Some,Box的用法,用来刷题的时间基本都没有了,所以只刷了一道。
题目如下:
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
题目翻译:
一个不为空的单链表表示一个非负整数,其中头部位低位,尾部为高位,计算两个数相加的结果。
题目思路:
从头部开始遍历,逐级相加,记得考虑进位
代码如下:
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 ret = Some(Box::new(ListNode::new(0)));
let (mut p1, mut p2, mut carry) = (l1, l2, 0);
let mut pos = ret.as_mut();
while p1.is_some() || p2.is_some() {
let mut sum = carry;
if let Some(v) = p1 {
sum += v.val;
p1 = v.next;
}
if let Some(v) = p2 {
sum += v.val;
p2 = v.next;
}
if sum >= 10 {
carry = 1;
sum = sum - 10;
} else {
carry = 0;
}
let v = pos.unwrap();
v.next = Some(Box::new(ListNode::new(sum)));
pos = v.next.as_mut();
}
if carry > 0 {
let v = pos.unwrap();
v.next = Some(Box::new(ListNode::new(1)));
}
return ret.unwrap().next;
}
#[test]
fn test_add_two_numbers() {
assert_eq!(1, 1);
let mut l1 = Box::new(ListNode::new(2));
l1.next = Some(Box::new(ListNode::new(4)));
l1.next.as_mut().unwrap().next= Some(Box::new(ListNode::new(7)));
let mut l2 = Box::new(ListNode::new(5));
l2.next = Some(Box::new(ListNode::new(6)));
l2.next.as_mut().unwrap().next = Some(Box::new(ListNode::new(4)));
let ret = add_two_numbers(Some(l1), Some(l2));
let expected_ret = [7, 0, 2, 1];
let mut pos = ret;
for i in (0..expected_ret.len()) {
assert_eq!(pos.is_some(), true);
if !pos.is_some() {
break;
}
if let Some(v) = pos {
assert_eq!(v.val, expected_ret[i]);
pos = v.next;
}
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。