Add Rust and C++ linked list implementations with build/debug configs
Rust version in src/main.rs (Cargo project) and a C++ port in cpp/main.cpp using raw pointers, both with VS Code build tasks and gdb-based debug configs. Vendors vscode-debug-visualizer and visualization as submodules for reference while building a custom node-table graph visualizer. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
57
src/main.rs
Normal file
57
src/main.rs
Normal file
@@ -0,0 +1,57 @@
|
||||
// A single node containing data and an optional pointer to the next node
|
||||
struct Node<T> {
|
||||
data: T,
|
||||
next: Option<Box<Node<T>>>,
|
||||
}
|
||||
|
||||
// The main wrapper for the linked list tracking the head node
|
||||
pub struct LinkedList<T> {
|
||||
head: Option<Box<Node<T>>>,
|
||||
}
|
||||
|
||||
impl<T> LinkedList<T> {
|
||||
// Create an empty linked list
|
||||
pub fn new() -> Self {
|
||||
LinkedList { head: None }
|
||||
}
|
||||
|
||||
// Add a new element to the front of the list
|
||||
pub fn push_front(&mut self, data: T) {
|
||||
let new_node = Box::new(Node {
|
||||
data,
|
||||
// .take() temporarily leaves None in self.head and extracts the value
|
||||
next: self.head.take(),
|
||||
});
|
||||
self.head = Some(new_node);
|
||||
}
|
||||
|
||||
// Remove and return the front element of the list
|
||||
pub fn pop_front(&mut self) -> Option<T> {
|
||||
self.head.take().map(|node| {
|
||||
self.head = node.next;
|
||||
node.data
|
||||
})
|
||||
}
|
||||
|
||||
// Read the front element without removing it
|
||||
pub fn peek_front(&self) -> Option<&T> {
|
||||
self.head.as_ref().map(|node| &node.data)
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let mut list = LinkedList::new();
|
||||
|
||||
// Demonstrate pushing items
|
||||
list.push_front(10);
|
||||
list.push_front(20);
|
||||
list.push_front(30);
|
||||
|
||||
// Demonstrate peaking at the top item
|
||||
println!("Top element: {:?}", list.peek_front()); // Output: Some(30)
|
||||
|
||||
// Demonstrate popping items
|
||||
while let Some(value) = list.pop_front() {
|
||||
println!("Popped: {}", value);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user