struct Stack {
data: [i32; 3],
top: usize,
}
impl Stack {
fn new() -> Self {
Stack { data: [0; 3], top: 0 }
}
fn push(&mut self, val: i32) {
if self.top < 3 {
self.data[self.top] = val;
self.top += 1;
}
}
fn pop(&mut self) -> Option<i32> {
if self.top == 0 {
None
} else {
self.top -= 1;
Some(self.data[self.top])
}
}
fn print_stack(&self) {
for i in (0..self.top).rev() {
print!("{} -> ", self.data[i]);
}
println!("null");
}
}
fn main() {
let mut stack = Stack::new();
stack.push(10);
stack.push(20);
stack.push(30);
stack.pop();
stack.push(40);
stack.print_stack();
}The stack starts empty. We push 10, 20, 30 in order. The stack is now 30 (top), 20, 10 (bottom). Then pop removes 30. Then push 40 adds 40 on top. So the stack is 40 (top), 20, 10 (bottom). Printing from top to bottom gives 40 -> 20 -> 10 -> null.
fn main() {
let mut stack = Stack::new();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4); // pushing beyond capacity
stack.print_stack();
}The push method only adds elements if top < 3. The fourth push is ignored because the stack is full. So the stack remains with 3 elements: 3 (top), 2, 1 (bottom). Printing shows 3 -> 2 -> 1 -> null.
struct Stack {
data: [i32; 3],
top: usize,
}
impl Stack {
fn new() -> Self {
Stack { data: [0; 3], top: 0 }
}
fn push(&mut self, val: i32) {
if self.top <= 3 {
self.data[self.top] = val;
self.top += 1;
}
}
fn pop(&mut self) -> Option<i32> {
if self.top == 0 {
None
} else {
let val = self.data[self.top - 1];
self.top -= 1;
Some(val)
}
}
}In pop, self.data[self.top] accesses an index equal to top, which is out of bounds since top points to next free slot. The correct index is self.top - 1 before decrementing top.
Arrays store elements contiguously in memory, which makes push and pop operations faster due to better cache usage. Linked lists require extra memory for pointers and have non-contiguous memory, which can slow access.
let mut stack = Stack::new(); stack.push(5); stack.push(10); stack.pop(); stack.push(15); stack.push(20); stack.pop(); stack.push(25); stack.print_stack();
Operations step-by-step:
push 5: stack = [5]
push 10: stack = [5,10]
pop: removes 10, stack = [5]
push 15: stack = [5,15]
push 20: stack = [5,15,20]
pop: removes 20, stack = [5,15]
push 25: stack = [5,15,25]
Printed top to bottom: 25 -> 15 -> 5 -> null
