feat: add initial implementation of reverse linked list

This commit is contained in:
SquidSpirit 2025-08-17 23:04:26 +08:00
parent 0eb65c4ed3
commit 11d6a65155
3 changed files with 57 additions and 0 deletions

7
206_reverse_linked_list/Cargo.lock generated Normal file
View File

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "reverse_linked_list"
version = "0.1.0"

View File

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

View File

@ -0,0 +1,44 @@
fn main() {
println!("Hello, world!");
}
#[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 }
}
}
struct Solution;
impl Solution {
pub fn reverse_list(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
let mut arr: Vec<i32> = vec![];
let mut current_node = head;
while current_node != None {
arr.push(current_node.as_ref().unwrap().val);
current_node = current_node.unwrap().next;
}
if arr.is_empty() {
return None;
}
let mut head = Some(Box::new(ListNode::new(*arr.last().unwrap())));
let mut current_node = &mut head;
for &num in arr[..arr.len() - 1].iter().rev() {
current_node.as_mut().unwrap().next = Some(Box::new(ListNode::new(num)));
current_node = &mut current_node.as_mut().unwrap().next;
}
head
}
}