Created
July 9, 2015 22:31
-
-
Save dash1291/47ba9956d2ae4681c770 to your computer and use it in GitHub Desktop.
fifo queue taking input from stdin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::io; | |
struct Node { | |
value: String, | |
next: Option<Box<Node>> | |
} | |
struct List { | |
head: Option<Box<Node>> | |
} | |
impl Node { | |
fn attach_new(&mut self, val: String) { | |
match self.next { | |
Some (ref mut next) => next.attach_new(val), | |
None => self.next = Some(Box::new(Node {value: val, next: None})) | |
} | |
} | |
} | |
impl List { | |
fn push_back(&mut self, val: String) { | |
match self.head { | |
Some(ref mut node) => node.attach_new(val), | |
None => self.head = Some(Box::new(Node {value: val, next: None})) | |
} | |
} | |
fn pull_front(&mut self) -> String { | |
if self.head.is_some() { | |
let detached_head = self.head.take().unwrap(); | |
let ret_val = detached_head.value.clone(); | |
self.head = detached_head.next; | |
return ret_val; | |
} else { | |
return "".to_string(); | |
} | |
} | |
} | |
fn input_reader(list: &mut List, input: String) -> Option<String> { | |
if input == "POP" { | |
return Some(list.pull_front()); | |
} else { | |
let pieces: Vec<&str> = input.split(" ").collect(); | |
if pieces[0] == "PUSH" { | |
list.push_back(pieces[1].to_string()); | |
} | |
return None; | |
} | |
} | |
fn main() { | |
let mut queue = List {head: None}; | |
let mut input = String::new(); | |
loop { | |
input = "".to_string(); | |
io::stdin().read_line(&mut input); | |
input = input.trim().to_string(); | |
if input.len() > 0 { | |
let s = input_reader(&mut queue, input); | |
match s { | |
Some(res) => println!("> {}", res), | |
None => continue | |
}; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment