Skip to content

Instantly share code, notes, and snippets.

@dmitryshelomanov
Created April 19, 2018 14:45
Show Gist options
  • Save dmitryshelomanov/64278d2495d75d8141e633785176b682 to your computer and use it in GitHub Desktop.
Save dmitryshelomanov/64278d2495d75d8141e633785176b682 to your computer and use it in GitHub Desktop.
use std::rc::{Rc, Weak};
use std::cell::RefCell;
type List = Option<Rc<RefCell<Node>>>;
type WeackList = Option<Weak<RefCell<Node>>>;
#[derive(Debug)]
struct Node {
data: i32,
next: List,
}
impl Node {
fn new(data: i32) -> Node {
Node {
data,
next: None,
}
}
fn append(&mut self, node: List) {
self.next = node
}
}
#[derive(Debug)]
struct LinkedList {
head: List,
tail: WeackList,
}
impl LinkedList {
fn new() -> LinkedList {
LinkedList {
head: None,
tail: None,
}
}
fn push(&mut self, data: i32) {
let node = Rc::new(RefCell::new(Node::new(data)));
match (self.tail.as_ref()) {
None => self.head = Some(Rc::clone(&node)),
Some(tail) => {
tail.upgrade().unwrap().borrow_mut().append(
Some(Rc::clone(&node))
)
}
}
self.tail = Some(Rc::downgrade(&node));
}
fn pop(&mut self) -> Option<i32> {
let old_head = self.head.take()
.map(|n| Rc::try_unwrap(n).unwrap())
.map(|n| n.into_inner());
old_head.map(|node| {
self.head = node.next;
node.data
})
}
}
fn main() {
let mut list = LinkedList::new();
list.push(1);
list.push(2);
list.push(3);
list.push(4);
list.pop();
list.pop();
list.pop();
list.pop();
println!("{:?}", list);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment