Created
February 26, 2020 13:09
-
-
Save SkyLightQP/1c96d4114e559872791ee67bdb0e8db0 to your computer and use it in GitHub Desktop.
러스트 초보의 단일 Linked List 만들어보기
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
#[derive(Debug)] | |
struct LinkedList<T> { | |
head: Option<Box<Node<T>>>, | |
length: usize | |
} | |
#[derive(Debug)] | |
struct Node<T> { | |
element: T, | |
next: Option<Box<Node<T>>> | |
} | |
impl<T> LinkedList<T> { | |
fn new() -> Self { | |
LinkedList { | |
head: None, | |
length: 0 | |
} | |
} | |
fn length(&self) -> usize { | |
self.length | |
} | |
fn push_front(&mut self, element: T) { | |
let node = Node { | |
element, | |
next: self.head.take() | |
}; | |
self.head = Some(Box::new(node)); | |
self.length += 1; | |
} | |
fn is_empty(&self) -> bool { | |
match self.length { | |
0 => true, | |
_ => false | |
} | |
} | |
fn pop_front(&mut self) { | |
if !self.is_empty() { | |
let prev_head = self.head.take(); | |
self.head = prev_head.unwrap().next; | |
} | |
} | |
fn peek(&self) -> Option<&T> { | |
match self.head { | |
Some(ref node) => { | |
Some(&node.element) | |
}, | |
None => None | |
} | |
} | |
} | |
fn main() { | |
let mut list = LinkedList::new(); | |
for i in (0..4).rev() { | |
list.push_front(i); | |
} | |
println!("front: {:?}", list.peek()); | |
list.pop_front(); | |
println!("front: {:?}", list.peek()); | |
list.push_front(5); | |
println!("front: {:?}", list.peek()); | |
println!("{:#?}", list); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment