Skip to content

Instantly share code, notes, and snippets.

@oscarcpozas
Last active February 8, 2023 16:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oscarcpozas/51d589c8197c8365d36b26e23f76dd91 to your computer and use it in GitHub Desktop.
Save oscarcpozas/51d589c8197c8365d36b26e23f76dd91 to your computer and use it in GitHub Desktop.
Linked list heap-allocated inspired on LISP lang
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"),
}
}
}
}
@oscarcpozas
Copy link
Author

Pseudocode representation: (1, (2, (3, None)))

@oscarcpozas
Copy link
Author

imagen

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment