Skip to content

Instantly share code, notes, and snippets.

@SkyLightQP
Created February 26, 2020 13:09
Show Gist options
  • Save SkyLightQP/1c96d4114e559872791ee67bdb0e8db0 to your computer and use it in GitHub Desktop.
Save SkyLightQP/1c96d4114e559872791ee67bdb0e8db0 to your computer and use it in GitHub Desktop.
러스트 초보의 단일 Linked List 만들어보기
#[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