slightly wasteful solution for remove-nth-from-back-of-linked-list
This commit is contained in:
parent
0ed2722260
commit
a3bcf6b12c
2 changed files with 67 additions and 0 deletions
8
remove_nth_from_list_end/Cargo.toml
Normal file
8
remove_nth_from_list_end/Cargo.toml
Normal file
|
@ -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]
|
59
remove_nth_from_list_end/src/main.rs
Normal file
59
remove_nth_from_list_end/src/main.rs
Normal file
|
@ -0,0 +1,59 @@
|
|||
// Definition for singly-linked list.
|
||||
#[derive(PartialEq, Eq, Clone, Debug)]
|
||||
pub struct ListNode {
|
||||
pub val: i32,
|
||||
pub next: Option<Box<ListNode>>,
|
||||
}
|
||||
|
||||
struct Solution();
|
||||
|
||||
impl Solution {
|
||||
pub fn remove_nth_from_end(head: Option<Box<ListNode>>, n: i32) -> Option<Box<ListNode>> {
|
||||
let stack = Solution::unmake(head);
|
||||
let ded = stack.len() - n as usize;
|
||||
let stack: Vec<i32> = 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<Box<ListNode>> {
|
||||
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<Box<ListNode>>) -> Vec<i32> {
|
||||
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<Box<ListNode>>) {
|
||||
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));
|
||||
}
|
Loading…
Reference in a new issue