225. 用队列实现栈

题目描述

请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。

实现 MyStack 类:

void push(int x) 将元素 x 压入栈顶。 int pop() 移除并返回栈顶元素。 int top() 返回栈顶元素。 boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。

解题思路

#![allow(unused)]

fn main() {
struct MyStack {
    q: std::collections::VecDeque<i32>,
}


/**
 * `&self` means the method takes an immutable reference.
 * If you need a mutable reference, change it to `&mut self` instead.
 */
impl MyStack {

    fn new() -> Self {
        Self { q: std::collections::VecDeque::new() }
    }
    
    fn push(&mut self, x: i32) {
        self.q.push_back(x);
    }
    
    fn pop(&mut self) -> i32 {
        let n = self.q.len();
        for _ in 1..n {
            let x = self.q.pop_front().unwrap();
            self.q.push_back(x);
        }
        self.q.pop_front().unwrap()
    }
    
    fn top(&mut self) -> i32 {
        let n = self.q.len();
        for _ in 1..n {
            let x = self.q.pop_front().unwrap();
            self.q.push_back(x);
        }
        let x = self.q.pop_front().unwrap();
        self.q.push_back(x);
        return x;
    }
    
    fn empty(&self) -> bool {
        self.q.is_empty()
    }
}

}

学习感想