Skip to content

Instantly share code, notes, and snippets.

@mitghi
Created August 24, 2021 12:43
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 mitghi/0f7d6a6c803bcda4cb47fad4157e652d to your computer and use it in GitHub Desktop.
Save mitghi/0f7d6a6c803bcda4cb47fad4157e652d to your computer and use it in GitHub Desktop.
Linked List in rust
struct Node {
value: i64,
next: Option<Box<Node>>,
}
struct List {
head: Option<Box<Node>>,
}
impl List {
fn new() -> List {
List{head: None}
}
fn push(&mut self, value: i64) {
let mut head = self.head.take();
let mut newHead = Node{value: value, next: head};
self.head = Some(Box::new(newHead));
}
fn pop(&mut self) -> Option<i64> {
match self.head {
None => None,
Some(_) => {
let mut v = self.head.take().unwrap();
let value = v.value;
self.head = v.next;
return Some(value);
}
}
}
}
fn main() -> () {
let mut l : List = List::new();
l.push(10);
l.push(20);
l.push(30);
l.push(40);
println!("{}", l.pop().unwrap());
println!("{}", l.pop().unwrap());
println!("{}", l.pop().unwrap());
println!("{}", l.pop().unwrap());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment