LeetCode 232 uses a stack to implement a queue, 225 uses a queue to implement a stack

232. Implement a queue with a stack

topic:

Please use only two stacks to implement a first-in-first-out queue. The queue should support all operations supported by general queues (push, pop, peek, empty):

Implement the MyQueue class:

  • void push(int x) pushes element x to the end of the queue
  • int pop() removes and returns an element from the beginning of the queue
  • int peek() returns the element at the head of the queue
  • boolean empty() returns true if the queue is empty; otherwise, returns false

illustrate:

  • You can only use standard stack operations - that is, only push to top, peek/pop from top, size, and is empty operations are legal.
  • Your language may not support stacks. You can use list or deque (double-ended queue) to simulate a stack, as long as it is a standard stack operation.
Example 1:
enter:
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
output:
[null, null, null, 1, 1, false]

explain:
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false

hint:
  • 1 <= x <= 9

  • Up to 100 calls to push, pop, peek and empty

  • Assume all operations are valid (e.g. an empty queue will not invoke pop or peek operations)

Advanced:
  • Can you implement a queue with O(1) amortized time complexity per operation? In other words, the total time complexity to perform n operations is O(n) even though one of the operations may take longer.

Stack: The stack is a last-in-first-out data structure, elements are pushed into the stack from the top, and then popped from the top

Queue: A queue is a first-in, first-out data structure. Elements enter the queue from the back end and then dequeue from the front end.

c++ code implementation
class MyQueue {
public:

    stack<int> inStack, outStack;

    MyQueue() {

    }
    
    void push(int x) {
        inStack.push(x);
    }
    
    int pop() {
        if (outStack.empty()){
            while (!inStack.empty()) {
                outStack.push(inStack.top());
                inStack.pop();
            }
        }
        int x = outStack.top();
        outStack.pop();
        return x;
    }
    
    int peek() {
        if (outStack.empty()) {
            while (!inStack.empty()) {
                outStack.push(inStack.top());
                inStack.pop();
            }
        }
        return outStack.top();
    }
    
    bool empty() {
        return inStack.empty() && outStack.empty();
    }
};

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue* obj = new MyQueue();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->peek();
 * bool param_4 = obj->empty();
 */
python code implementation
class MyStack:
    def __init__(self):
        self.stack = []
    
    def top(self):
        return self.stack[-1]

    def push(self, x:int) -> None:
        self.stack.append(x)
    
    def pop(self) -> int:
        return self.stack.pop()

    def empty(self) -> bool:
        return (len(self.stack) == 0)

class MyQueue:

    def __init__(self):
        self.inStack = MyStack()
        self.outStack = MyStack()

    def push(self, x: int) -> None:
        self.inStack.push(x)

    def pop(self) -> int:
        if self.outStack.empty():
            while self.inStack.empty() != True:
                self.outStack.push(self.inStack.top())
                self.inStack.pop()
        x = self.outStack.top()
        self.outStack.pop()
        return x

    def peek(self) -> int:
        if self.outStack.empty():
            while self.inStack.empty() != True:
                self.outStack.push(self.inStack.top())
                self.inStack.pop()
        return self.outStack.top()

    def empty(self) -> bool:
        return self.inStack.empty() and  self.outStack.empty()



# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()

225 Implementing a stack with a queue

topic:

Please use only two queues to implement a last-in-first-out (LIFO) stack, and support all four operations (push, top, pop, and empty) of a normal stack.

Implement the MyStack class:

  • void push(int x) pushes the element x onto the top of the stack.
  • int pop() removes and returns the top element of the stack.
  • int top() Returns the top element of the stack.
  • boolean empty() Returns true if the stack is empty; otherwise, returns false .

Notice:

  • You can only use the basic operations of the queue - namely push to back, peek/pop from front, size and is empty.
  • Your language may not support queues. You can use list (list) or deque (double-ended queue) to simulate a queue, as long as it is a standard queue operation.
Example:
enter:
["MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]
output:
[null, null, null, 2, 2, false]

explain:
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // return 2
myStack.pop(); // return 2
myStack.empty(); // returns False
hint:
  • 1 <= x <= 9
  • Up to 100 calls to push, pop, top and empty
  • Each call to pop and top ensures that the stack is not empty
c++ code implementation
class MyStack {
public:
    queue<int> inDeque;

    MyStack() {
    }
    
    void push(int x) {
        int n = inDeque.size();
        inDeque.push(x);
        for (int i = 0; i < n; i++) {
            inDeque.push(inDeque.front());
            inDeque.pop();
        }
    }
    
    int pop() {
        int x = inDeque.front();
        inDeque.pop();
        return x;
    }
    
    int top() {
        return inDeque.front();
    }
    
    bool empty() {
        return inDeque.empty();
    }
};

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack* obj = new MyStack();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->top();
 * bool param_4 = obj->empty();
 */
python code implementation
class MyStack:

    def __init__(self):
        self.queque = collections.deque()


    def push(self, x: int) -> None:
        n = len(self.queque)
        self.queque.append(x)
        for i in range(n):
            self.queque.append(self.queque.popleft())
        
    def pop(self) -> int:
        return self.queque.popleft()


    def top(self) -> int:
        return self.queque[0]


    def empty(self) -> bool:
        return not self.queque

# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()

Tags: Python Algorithm data structure leetcode

Posted by planethax on Wed, 16 Nov 2022 02:28:04 +0300