How should I implement a linked list in Rust? Keep in mind, this is for an embedded…
- User
How should I implement a linked list in Rust? Keep in mind, this is for an embedded project so it's
no_stdand no heap allocation - Assistant
In Rust, implementing a linked list without using the standard library (
no_std) and avoiding heap allocations can be a bit challenging, but it's definitely possible. Here's a simple implementation of a singly linked list using an array-based stack for storage:rust#![no_std] pub struct Node<T> { value: T, next: Option<usize>, } pub struct LinkedList<T> { nodes: [Option<Node<T>>; 10], // Adjust the size as needed head: usize, tail: usize, len: usize, } impl<T> LinkedList<T> { pub fn new() -> Self { LinkedList { nodes: [None; 10], head: 0, tail: 0, len: 0, } } pub fn push(&mut self, value: T) { if self.len == self.nodes.len() { // Handle the case when the list is full return; } let node_index = self.tail; let next_index = if self.len == self.nodes.len() - 1 { None } else { Some(node_index + 1) }; self.nodes[node_index] = Some(Node { value, next: next_index }); self.tail = if self.len == self.nodes.len() - 1 { 0 } else { node_index + 1 }; self.len += 1; if self.len == 1 { self.head = node_index; } } pub fn pop(&mut self) -> Option<T> { if self.len == 0 { return None; } let node = self.nodes[self.head].take(); self.head = node.as_ref().map(|n| n.next.unwrap()).unwrap_or(0); self.len -= 1; node.map(|n| n.value) } pub fn peek(&self) -> Option<&T> { self.nodes[self.head].as_ref().map(|n| &n.value) } pub fn len(&self) -> usize { self.len } pub fn is_empty(&self) -> bool { self.len == 0 } } #[cfg(test)] mod tests { use super::*; #[test] fn test_linked_list() { let mut list: LinkedList<i32> = LinkedList::new(); assert!(list.is_empty()); list.push(1); list.push(2); list.push(3); assert_eq!(list.len(), 3); assert_eq!(list.pop(), Some(1)); assert_eq!(list.pop(), Some(2)); assert_eq!(list.pop(), Some(3)); assert!(list.is_empty()); } }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.