Using stack to implement queue leetcode

Title Description

Use the stack to implement the following operations of the queue:

push(x) -- puts an element at the end of the queue.
pop() -- removes the element from the head of the queue.
peek() -- returns the element at the beginning of the queue.
empty() -- returns whether the queue is empty.

Stack: first in, then out;
Queue: first in first out;

Train of thought:
1. Use two stacks stack and queue;
2. push the data into the stack;
3. When the queue is queued, it is a stack in the stack. If the queue has no data, it is a stack in the stack. If the queue has data, it is a stack;

 Stack<int> stack = new Stack<int>();
        Stack<int> queue = new Stack<int>();

        public MyQueue()
        {
        }

        public void Push(int x)
        {
            stack.push(x);
        }

        public int Pop()
        {
            if (queue.isEmpty())
            {
                while (stack.top != null)
                {
                    queue.push(stack.peek());
                    stack.pop();
                }                
            }
            int topV = queue.peek();
            queue.pop();
            return topV;
        }

        /** Get the front element. */
        public int Peek()
        {
            if (queue.isEmpty())
            {
                while (stack.top != null)
                {
                    queue.push(stack.peek());
                    stack.pop();
                }
            }
            return queue.peek();
        }

        /** Returns whether the queue is empty. */
        public bool Empty()
        {
            if (queue.isEmpty())
            {
                while (stack.top != null)
                {
                    queue.push(stack.peek());
                    stack.pop();
                }
            }
            if (queue.top == null) return false;
            return true;
        }

Posted by yanisdon on Sun, 08 Dec 2019 14:45:27 -0800