Skip to content

Instantly share code, notes, and snippets.

@michaelsproul
Created April 15, 2014 23:57
Show Gist options
  • Save michaelsproul/10790759 to your computer and use it in GitHub Desktop.
Save michaelsproul/10790759 to your computer and use it in GitHub Desktop.
Rust Linked List (with owned pointers)
enum LinkedList
{
Node(int, ~LinkedList),
Nil
}
impl LinkedList
{
fn push_front(&mut self, x: int)
{
*self = self.push_front_r(x);
}
fn push_front_r(&mut self, x: int) -> LinkedList
{
match *self
{
Node(v, ref mut next) => Node(x, ~next.push_front_r(v)),
Nil => Node(x, ~Nil)
}
}
fn push_back(&mut self, x: int)
{
match *self
{
Node(_, ref mut next) => next.push_back(x),
Nil => *self = Node(x, ~Nil)
}
}
}
fn pop_front(list: ~LinkedList) -> (int, ~LinkedList)
{
let mut value: int = -1;
let new_list: ~LinkedList = match *list
{
Node(v, next) => {value = v; next},
Nil => ~Nil
};
return (value, new_list);
}
fn main()
{
let mut list: ~LinkedList = ~Nil;
list.push_back(7);
list.push_front(2);
list.push_front(100);
list.push_front(10);
list.push_back(67);
let mut value: int;
for _ in range(0, 5)
{
match pop_front(list)
{
(v, new_list) => {value = v; list = new_list}
}
println!("{:d}", value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment