feat: add initial implementation of reverse linked list
This commit is contained in:
parent
0eb65c4ed3
commit
11d6a65155
7
206_reverse_linked_list/Cargo.lock
generated
Normal file
7
206_reverse_linked_list/Cargo.lock
generated
Normal 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"
|
6
206_reverse_linked_list/Cargo.toml
Normal file
6
206_reverse_linked_list/Cargo.toml
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
[package]
|
||||||
|
name = "reverse_linked_list"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
|
||||||
|
[dependencies]
|
44
206_reverse_linked_list/src/main.rs
Normal file
44
206_reverse_linked_list/src/main.rs
Normal 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
|
||||||
|
}
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user