1. Introduction
A Stack is a linear data structure that follows the Last In First Out (LIFO) principle. This means the last element added to the stack will be the first element to be removed. It's analogous to a stack of plates; you can only add or remove plates from the top of the stack.
2. Implementation Steps
1. Define the Stack struct that will contain a Vec to store the stack elements.
2. Implement a new function to initialize the stack.
3. Implement a push function to add an element to the top of the stack.
4. Implement a pop function to remove the top element of the stack.
5. Implement a peek function to view the top element without removing it.
6. Implement an is_empty function to check if the stack is empty.
3. Implementation in Rust Programming
// Defining the Stack struct
pub struct Stack<T> {
elements: Vec<T>,
}
impl<T> Stack<T> {
// Initialize an empty stack
pub fn new() -> Self {
Stack {
elements: Vec::new(),
}
}
// Add an element to the top of the stack
pub fn push(&mut self, value: T) {
self.elements.push(value);
}
// Remove and return the top element of the stack
pub fn pop(&mut self) -> Option<T> {
self.elements.pop()
}
// View the top element without removing it
pub fn peek(&self) -> Option<&T> {
self.elements.last()
}
// Check if the stack is empty
pub fn is_empty(&self) -> bool {
self.elements.is_empty()
}
}
fn main() {
let mut stack: Stack<i32> = Stack::new();
stack.push(5);
stack.push(10);
stack.push(15);
println!("Top of the stack: {:?}", stack.peek());
println!("Popped from stack: {:?}", stack.pop());
println!("Top of the stack after pop: {:?}", stack.peek());
println!("Is the stack empty? {}", stack.is_empty());
}
Output:
Top of the stack: Some(15) Popped from stack: Some(15) Top of the stack after pop: Some(10) Is the stack empty? false
Explanation:
1. The Stack struct is defined to hold elements using a Vec. The generic type T allows it to store any type of element.
2. The new function initializes an empty stack.
3. The push function adds an element to the top of the stack.
4. The pop function removes and returns the top element. If the stack is empty, it returns None.
5. The peek function provides a way to view the top element without removing it. If the stack is empty, it returns None.
6. The is_empty function checks if the stack is empty.
7. The main function demonstrates using the stack by pushing elements onto it, peeking at the top element, popping an element, and checking if it's empty.
Comments
Post a Comment