SHARE
TWEET

Untitled

a guest Sep 22nd, 2019 83 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. use std::mem::{replace};
  2.  
  3. #[derive(Debug)]
  4. enum Link {
  5.     Nil,
  6.     Cons(Box<Node>)
  7. }
  8.  
  9. #[derive(Debug)]
  10. struct Node {
  11.     element: i32,
  12.     next: Link
  13. }
  14.  
  15. #[derive(Debug)]
  16. pub struct List {
  17.     head: Link
  18. }
  19.  
  20. impl List {
  21.     pub fn new() -> Self {
  22.         List { head: Link::Nil }
  23.     }
  24.  
  25.     pub fn push(&mut self, v: i32) {
  26.         self.head = Link::Cons(Box::new(
  27.             Node {
  28.                 element: v,
  29.                 next: replace(&mut self.head, Link::Nil)
  30.             }
  31.         ));
  32.     }
  33.  
  34.     pub fn pop(&mut self) -> Option<i32> {
  35.         match replace(&mut self.head, Link::Nil) {
  36.             Link::Nil => None,
  37.             Link::Cons(node) => {
  38.                 self.head = node.next;
  39.                 Some(node.element)
  40.             }
  41.         }
  42.     }
  43. }
  44.  
  45. fn main() {
  46.     let mut l = List::new();
  47.     l.push(19);
  48.     l.push(20);
  49.  
  50.     println!("{:?}", l);
  51.     println!("{:?}", l.pop());
  52.     println!("{:?}", l);
  53. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top