Skip to content

Instantly share code, notes, and snippets.

@officialcjunior
Created July 11, 2021 08:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save officialcjunior/29560bb947bdef5561de62c96199e247 to your computer and use it in GitHub Desktop.
Save officialcjunior/29560bb947bdef5561de62c96199e247 to your computer and use it in GitHub Desktop.
Implementation of a singly linked list in Rust using smart pointers(Box)
use std::fmt;
use std::io;
// Since, we don't have `NULL` in Rust, we will use Option for
// each of the smart pointers- `Box`es. Basically, each of the Node contains a
// Some() or a None()
struct Node {
value: u32,
next: Option<Box<Node>>,
}
// We're defining the struct here. We'll have a Node that we
// declared earlier as the head pointer and we'll also have the
// size of the list.
pub struct LinkedList {
head: Option<Box<Node>>,
size: usize,
}
// Returns a new node
impl Node {
fn new(value: u32, next: Option<Box<Node>>) -> Node {
Node {
value: value,
next: next,
}
}
}
impl LinkedList {
pub fn new() -> LinkedList {
LinkedList {
head: None,
size: 0,
}
}
pub fn get_size(&self) -> usize {
self.size
}
pub fn is_empty(&self) -> bool {
self.size == 0
}
pub fn push(&mut self, value: u32) {
let new_node = Box::new(Node::new(value, self.head.take()));
self.head = Some(new_node);
self.size += 1;
}
pub fn pop(&mut self) -> Option<u32> {
let node = self.head.take()?;
self.head = node.next;
self.size -= 1;
Some(node.value)
}
}
// Here, we're implementing fmt::Display for Linkedlist so
// that we can println!("{}") the list - just like that
impl fmt::Display for LinkedList {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut current: &Option<Box<Node>> = &self.head;
let mut result = String::new();
loop {
match current {
Some(node) => {
result = format!("{} {}", result, node.value);
current = &node.next;
}
None => break,
}
}
write!(f, "{}", result)
}
}
impl Drop for LinkedList {
fn drop(&mut self) {
let mut current = self.head.take();
while let Some(mut node) = current {
current = node.next.take();
}
}
}
fn get_input() -> String {
let mut buffer = String::new();
io::stdin().read_line(&mut buffer).expect("Failed to take input");
buffer
}
// We'll get one number from STDIN and then we'll just push one number
// for the sake of simplicity
//
// Here we can println! the list because we have implement fmt::Display
fn main() {
let n = get_input().trim().parse::<i64>().unwrap();
let mut a = LinkedList::new();
a.push(n as u32);
a.push(2);
println!("{}", a);
a.pop();
println!("{}", a);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment