jason89521 / leetcode_note

0 stars 0 forks source link

232. Implement Queue using Stacks #7

Open jason89521 opened 3 months ago

jason89521 commented 3 months ago

Practice Dates

Description

Link: https://leetcode.com/problems/implement-queue-using-stacks/description/

Solution

Use two stack to implement a queue, the in_stack is for storing the incoming value, the out_stack is for accessing the first-in value. When we want to mutate the queue, we should check whether the out_stack is empty before or after mutating the queue.

struct MyQueue {
    in_stack: Vec<i32>,
    out_stack: Vec<i32>
}

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

    fn new() -> Self {
        Self {
            in_stack: vec![],
            out_stack: vec![]
        }
    }

    fn push(&mut self, x: i32) {
        if self.out_stack.is_empty() {
            self.out_stack.push(x);
        } else {
            self.in_stack.push(x);
        }
    }

    fn pop(&mut self) -> i32 {
        let ret = self.out_stack.pop().unwrap();
        if self.out_stack.is_empty() {
            while !self.in_stack.is_empty() {
                self.out_stack.push(self.in_stack.pop().unwrap());
            }
        }

        ret
    }

    fn peek(&self) -> i32 {
        *self.out_stack.last().unwrap()
    }

    fn empty(&self) -> bool {
        self.in_stack.is_empty() && self.out_stack.is_empty()
    }
}

/**
 * Your MyQueue object will be instantiated and called as such:
 * let obj = MyQueue::new();
 * obj.push(x);
 * let ret_2: i32 = obj.pop();
 * let ret_3: i32 = obj.peek();
 * let ret_4: bool = obj.empty();
 */

Performance

Time complexity: