-
-
Save the-shank/f2e545087e3cb226b77ef2178488ec30 to your computer and use it in GitHub Desktop.
DS - Rust - Singly Linked List
This file contains hidden or 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
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