Last active
February 8, 2023 16:48
-
-
Save oscarcpozas/51d589c8197c8365d36b26e23f76dd91 to your computer and use it in GitHub Desktop.
Linked list heap-allocated inspired on LISP lang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pub struct Cons<T> { | |
pub value: T, | |
pub next: Option<Box<Cons<T>>>, | |
pub index: usize, | |
} | |
impl <T> Cons<T> { | |
pub fn new(value: T) -> Cons<T> { | |
Cons { value, next: None, index: 0, } | |
} | |
fn inner_new(value: T, next: Option<Box<Cons<T>>>, index: usize) -> Cons<T> { | |
let next = match next { | |
Some(next) => Some(Box::new(Cons::inner_new(value, Some(next), index + 1))), | |
None => None, | |
}; | |
Cons { | |
value: cons.value, | |
next, | |
index: cons.index | |
} | |
} | |
pub fn get(&self, index: usize) -> &T { | |
if index == self.index { | |
return &self.value; | |
} else { | |
match &self.next { | |
Some(next) => next.get(index), | |
None => unreachable!("Index out of bounds"), | |
} | |
} | |
} | |
pub fn add(&mut self, value: T, index: usize) { | |
if index == self.index { | |
self.next = Some(Box::new(Cons::inner_new(value, self.next.take(), index))); | |
} else { | |
match &mut self.next { | |
Some(next) => next.add(value, index), | |
None => self.next = Some(Box::new(Cons::new(value))), | |
} | |
} | |
} | |
pub fn remove(&mut self, index: usize) { | |
if index == self.index { | |
self.next = self.next.take().unwrap().next.take(); | |
} else { | |
match &mut self.next { | |
Some(next) => next.remove(index), | |
None => unreachable!("Index out of bounds"), | |
} | |
} | |
} | |
} |
Author
oscarcpozas
commented
Feb 8, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment