A stack is a pile where you only touch the top: the last value you put in is the first one you take out (LIFO, last in, first out), like a pile of plates. Build a class MyStack that stores whole numbers in a data: Vec<i32> field in struct MyStack and offers four operations.
The methods:
fn push(&mut self, value: i32)fn pop(&mut self) -> i32fn peek(&self) -> i32fn size(&self) -> usize
Rules:
pushputs the value on top of the stack. It returns nothing.popremoves the top value (the one pushed last) and returns it.peekreturns the top value but leaves it on the stack, so the size does not change.sizereturns how many values are on the stack. A new stack has size 0, and after popping everything the size is 0 again.- The stack keeps working after it becomes empty: you can push again.
- Calling
poporpeekon an empty stack is not part of this exercise and the tests never do it. (In Rust,unwrap()on an empty stack panics.)
You start with: The starter has an empty mainFunction: type this code inside it after the class.
let mut s = MyStack::new();
s.push(10);
s.push(20);
s.push(30);
println!("Top: {}", s.peek());
println!("Size: {}", s.size());
println!("Pop: {}", s.pop());
println!("Size: {}", s.size());
println!("Pop: {}", s.pop());
println!("Pop: {}", s.pop());
println!("Empty size: {}", s.size());
s.push(7);
println!("Top: {}", s.peek());
println!("Size: {}", s.size());
Expected output:
Top: 30 Size: 3 Pop: 30 Size: 2 Pop: 20 Pop: 10 Empty size: 0 Top: 7 Size: 1
Reading the output: after pushing 10, 20 and 30 the top is 30 and the size 3. Popping gives 30, leaving size 2. Two more pops give 20 and then 10 (last in, first out), the stack is empty (size 0), and after pushing 7 the top is 7 and the size 1.
The top of the stack is the end of the list: adding and removing at the end is fast, and the last value pushed is always the last element.
A
Vec has push, pop() (returns an Option, so call .unwrap()) and last() (an Option<&i32>, so write *self.data.last().unwrap()). Add a fn new() -> MyStack that returns MyStack { data: Vec::new() }. Methods that change the stack take &mut self.
struct MyStack {
data: Vec<i32>,
}
impl MyStack {
fn new() -> MyStack {
MyStack { data: Vec::new() }
}
fn push(&mut self, value: i32) {
self.data.push(value);
}
fn pop(&mut self) -> i32 {
self.data.pop().unwrap()
}
fn peek(&self) -> i32 {
*self.data.last().unwrap()
}
fn size(&self) -> usize {
self.data.len()
}
}
Free plan: 30 tutor messages. Premium is unlimited.
