remove a node from the beginning of a linked list in rust

To remove a node from the beginning of a linked list in Rust, we need to do the following steps:

  1. Check whether the linked list is empty
  2. If not empty, get a reference to the first node
  3. Set the next node of the linked list as the new head
  4. Return the removed node

Here's the Rust code to remove a node from the beginning of a linked list:

main.rs
struct Node<T> {
    value: T,
    next: Option<Box<Node<T>>>,
}

impl<T> Node<T> {
    fn new(value: T) -> Self {
        Node { value, next: None }
    }
}

struct LinkedList<T> {
    head: Option<Box<Node<T>>>,
}

impl<T> LinkedList<T> {
    fn new() -> Self {
        LinkedList { head: None }
    }

    fn remove_first(&mut self) -> Option<T> {
        if let Some(mut node) = self.head.take() {
            // get the value of the removed node
            let value = node.value;

            // set the next node as the new head
            self.head = node.next.take();

            Some(value)
        } else {
            None
        }
    }
}
656 chars
35 lines

In this code, we first define a Node struct to represent a node in the linked list, and a LinkedList struct to represent the linked list itself. The remove_first method of the LinkedList struct removes the first node from the linked list and returns its value.

We use the Option type to represent the case where the linked list is empty, and the Box type to represent the fact that each node points to the next node in the linked list. We use the take method to remove the head of the linked list and set the next node as the new head.

gistlibby LogSnag