Sha256: bcbf35470c76fe2cae01f3e9dbb9f3aa96bb2d4e141c1b9f37849b85a9d37df7
Contents?: true
Size: 1.9 KB
Versions: 106
Compression:
Stored size: 1.9 KB
Contents
pub struct SimpleLinkedList<T> { head: Option<Box<Node<T>>>, len: usize, } struct Node<T> { data: T, next: Option<Box<Node<T>>>, } impl<T> SimpleLinkedList<T> { pub fn new() -> Self { SimpleLinkedList { head: None, len: 0 } } pub fn len(&self) -> usize { self.len } pub fn push(&mut self, element: T) { let node = Box::new(Node::new(element, self.head.take())); self.head = Some(node); self.len += 1; } pub fn pop(&mut self) -> Option<T> { match self.len { 0 => None, _ => { self.len -= 1; self.head.take().map(|node| { let node = *node; self.head = node.next; node.data }) } } } pub fn peek(&self) -> Option<&T> { self.head.as_ref().map(|node| &node.data) } } impl<T: Clone> SimpleLinkedList<T> { pub fn rev(&self) -> SimpleLinkedList<T> { let mut rev_list = SimpleLinkedList::new(); let mut next = self.head.as_ref().map(|node| &**node); while let Some(node) = next { rev_list.push(node.data.clone()); next = node.next.as_ref().map(|node| &**node); } rev_list } } impl<'a, T: Clone> From<&'a [T]> for SimpleLinkedList<T> { fn from(item: &[T]) -> Self { let mut list = SimpleLinkedList::new(); for i in item { list.push(i.clone()); } list } } impl<T> Into<Vec<T>> for SimpleLinkedList<T> { fn into(mut self) -> Vec<T> { let mut vec = Vec::new(); while let Some(data) = self.pop() { vec.push(data); } vec.reverse(); vec } } impl<T> Node<T> { pub fn new(element: T, next: Option<Box<Node<T>>>) -> Self { Node { data: element, next, } } }
Version data entries
106 entries across 106 versions & 1 rubygems