From a3bcf6b12cd004989e1b152476e7d3ee4a5f0e2b Mon Sep 17 00:00:00 2001 From: Joe Ardent Date: Tue, 1 Nov 2022 14:35:20 -0700 Subject: [PATCH] slightly wasteful solution for remove-nth-from-back-of-linked-list --- remove_nth_from_list_end/Cargo.toml | 8 ++++ remove_nth_from_list_end/src/main.rs | 59 ++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 remove_nth_from_list_end/Cargo.toml create mode 100644 remove_nth_from_list_end/src/main.rs diff --git a/remove_nth_from_list_end/Cargo.toml b/remove_nth_from_list_end/Cargo.toml new file mode 100644 index 0000000..06c36b3 --- /dev/null +++ b/remove_nth_from_list_end/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "remove_nth_from_list_end" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/remove_nth_from_list_end/src/main.rs b/remove_nth_from_list_end/src/main.rs new file mode 100644 index 0000000..2e3cf47 --- /dev/null +++ b/remove_nth_from_list_end/src/main.rs @@ -0,0 +1,59 @@ +// Definition for singly-linked list. +#[derive(PartialEq, Eq, Clone, Debug)] +pub struct ListNode { + pub val: i32, + pub next: Option>, +} + +struct Solution(); + +impl Solution { + pub fn remove_nth_from_end(head: Option>, n: i32) -> Option> { + let stack = Solution::unmake(head); + let ded = stack.len() - n as usize; + let stack: Vec = stack + .into_iter() + .enumerate() + .filter_map(|e| if e.0 != ded { Some(e.1) } else { None }) + .collect(); + + Solution::make(&stack) + } + + pub fn make(list: &[i32]) -> Option> { + let mut head = None; + for &val in list.iter().rev() { + let tail = head.clone(); + let node = Box::new(ListNode { val, next: tail }); + head = Some(node); + } + head + } + + pub fn unmake(mut list: Option>) -> Vec { + let mut v = Vec::with_capacity(30); + while let Some(node) = list { + v.push(node.val); + list = node.next; + } + v + } +} + +fn print(mut list: Option>) { + print!("["); + while let Some(node) = list { + print!("{} ", node.val); + list = node.next; + } + println!("]"); +} + +fn main() { + print(Solution::remove_nth_from_end( + Solution::make(&[1, 2, 3, 4, 5]), + 2, + )); + + print(Solution::remove_nth_from_end(Solution::make(&[1]), 1)); +}