Skip to content

Instantly share code, notes, and snippets.

@the-shank
Forked from rust-play/playground.rs
Last active August 9, 2019 05:03
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 the-shank/f2e545087e3cb226b77ef2178488ec30 to your computer and use it in GitHub Desktop.
Save the-shank/f2e545087e3cb226b77ef2178488ec30 to your computer and use it in GitHub Desktop.
DS - Rust - Singly Linked List
use std::cell::RefCell;
use std::rc::Rc;
#[derive(Clone)]
struct Node {
value: String,
next: SingleLink,
}
impl Node {
fn new(value: String) -> Rc<RefCell<Node>> {
Rc::new(RefCell::new(Node {
value: value,
next: None,
}))
}
}
type SingleLink = Option<Rc<RefCell<Node>>>;
struct TransactionLog {
head: SingleLink,
tail: SingleLink,
pub length: u64,
}
impl TransactionLog {
pub fn new_empty() -> Self {
Self {
head: None,
tail: None,
length: 0,
}
}
pub fn append(&mut self, value: String) {
let new = Node::new(value);
match self.tail.take() {
Some(old) => old.borrow_mut().next = Some(new.clone()),
None => self.head = Some(new.clone()),
}
self.length += 1;
self.tail = Some(new);
}
pub fn pop(&mut self) -> Option<String> {
self.head.take().map(|head| {
if let Some(next) = head.borrow_mut().next.take() {
// more than one elements in the list
self.head = Some(next);
} else {
// only 1 element in the list
self.tail.take();
}
self.length -= 1;
Rc::try_unwrap(head).ok().expect("BOOM!").into_inner().value
})
}
}
fn main() {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment