create a linked list in rust

main.rs
// Define a node struct which will hold data and a pointer to the next node
struct Node<T> {
    data: T,
    next: Option<Box<Node<T>>>,
}

// Define a linked list struct which will hold a pointer to the head node
struct LinkedList<T> {
    head: Option<Box<Node<T>>>,
}

// Implementation of the linked list
impl<T> LinkedList<T> {
    // Function to create an empty linked list
    fn new() -> Self {
        LinkedList { head: None }
    }

    // Function to add a new node to the linked list
    fn push(&mut self, data: T) {
        let new_node = Node {
            data: data,
            next: self.head.take(),
        };
        self.head = Some(Box::new(new_node));
    }

    // Function to remove the first node of the linked list
    fn pop(&mut self) -> Option<T> {
        self.head.take().map(|node| {
            self.head = node.next;
            node.data
        })
    }

    // Function to check if the linked list is empty
    fn is_empty(&self) -> bool {
        self.head.is_none()
    }
}

// Example usage
fn main() {
    let mut list = LinkedList::new();
    list.push(1);
    list.push(2);
    list.push(3);

    while !list.is_empty() {
        println!("{}", list.pop().unwrap());
    }
}
1223 chars
53 lines

This implementation creates a generic linked list data structure in Rust, allowing you to store any type of data in the list. The Node struct represents a single node in the linked list, with a field for the data held in the node and a field for a pointer to the next node in the list. The LinkedList struct represents the linked list data structure as a whole, holding a pointer to the head node of the list.

The implementation includes functions to push new nodes onto the front of the linked list, pop the first node off the front of the list, and check if the list is empty. In the example usage code, we create a new linked list, push some integers onto the list, and then pop them off one at a time and print them.

gistlibby LogSnag