Skip to content

Instantly share code, notes, and snippets.

@Antsiscool
Created February 16, 2015 12:18
Show Gist options
  • Save Antsiscool/a1ff61b325c1741728dc to your computer and use it in GitHub Desktop.
Save Antsiscool/a1ff61b325c1741728dc to your computer and use it in GitHub Desktop.
Print a linked list in reverse
#![feature(box_syntax)]
struct Node {
data: u32,
next: Option<Box<Node>>,
}
impl Node {
fn new(data: u32) -> Self {
Node {data: data, next: None}
}
fn insert(&mut self, data: u32) {
if !self.next.is_some() {
self.next = Some(box Node::new(data));
}
else {
(*self.next.as_mut().unwrap()).insert(data);
}
}
}
struct LinkedList {
first: Option<Box<Node>>,
}
impl LinkedList {
fn new() -> Self {
LinkedList{first: None}
}
fn push(&mut self, data: u32) {
self.first = Some(box Node {
data: data,
next: self.first.take(),
})
}
fn pop(&mut self) -> Option<u32> {
match self.first.take() {
None => None,
Some(mut first) => {
self.first = first.next.take();
Some(first.data)
}
}
}
fn insert(&mut self, data: u32) {
if !self.first.is_some() {
let node = Box::new(Node::new(data));
self.first = Some(node);
}
else {
(*self.first.as_mut().unwrap()).insert(data);
}
}
fn reverse(&mut self) {
let mut temp = LinkedList::new();
while let Some(x) = self.pop() {
temp.push(x);
}
self.first = temp.first.take();
}
fn print(&self) {
let mut current = self.first.as_ref();
while current.is_some() {
print!("{} ", current.unwrap().data);
current = current.unwrap().next.as_ref();
}
println!("");
}
fn print_in_reverse(&mut self) {
self.reverse();
self.print();
self.reverse();
}
}
fn main() {
let mut list = LinkedList::new();
list.insert(1);
list.insert(2);
list.insert(3);
list.insert(4);
list.insert(5);
list.insert(6);
list.insert(7);
list.insert(8);
list.insert(9);
list.insert(10);
list.print();
list.print_in_reverse();
list.print();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment