use std::rc::Rc;
use std::cell::RefCell;
// Node for singly linked list
#[derive(Debug)]
struct Node {
val: i32,
next: Option<Rc<RefCell<Node>>>,
}
impl Node {
fn new(val: i32) -> Rc<RefCell<Node>> {
Rc::new(RefCell::new(Node { val, next: None }))
}
}
// Linked list with head pointer
struct LinkedList {
head: Option<Rc<RefCell<Node>>>,
}
impl LinkedList {
fn new() -> Self {
LinkedList { head: None }
}
// Add at start by creating new node pointing to old head
fn add_at_start(&mut self, val: i32) {
let new_node = Node::new(val);
new_node.borrow_mut().next = self.head.take();
self.head = Some(new_node);
}
// Access nth item by following pointers
fn get_nth(&self, n: usize) -> Option<i32> {
let mut current = self.head.clone();
let mut count = 0;
while let Some(node) = current {
if count == n {
return Some(node.borrow().val);
}
current = node.borrow().next.clone();
count += 1;
}
None
}
// Print list as string
fn to_string(&self) -> String {
let mut result = String::new();
let mut current = self.head.clone();
while let Some(node) = current {
result.push_str(&format!("{} -> ", node.borrow().val));
current = node.borrow().next.clone();
}
result.push_str("null");
result
}
}
fn main() {
// Array example
let mut array = vec![1, 2, 3, 4, 5];
// Add 0 at start by shifting
array.insert(0, 0);
println!("Array after add at start: {:?}", array);
// Access third item (index 2)
println!("Array third item: {}", array[2]);
// Linked list example
let mut list = LinkedList::new();
// Build list 1->2->3->4->5
for &v in &[5, 4, 3, 2, 1] {
list.add_at_start(v);
}
// Add 0 at start
list.add_at_start(0);
println!("Linked List after add at start: {}", list.to_string());
// Access third item (index 2)
if let Some(val) = list.get_nth(2) {
println!("Linked List third item: {}", val);
} else {
println!("Linked List third item: None");
}
}
Shift all elements right to add at start in array
println!("Array third item: {}", array[2]);
Direct access to third item by index in array
Add new node at start by pointing to old head in linked list
Add 0 at start of linked list by changing head pointer
Traverse linked list nodes to find third item
Array after add at start: [0, 1, 2, 3, 4, 5]
Array third item: 2
Linked List after add at start: 0 -> 1 -> 2 -> 3 -> 4 -> 5 -> null
Linked List third item: 2