Java, same logic as implementing Stack using Queue


  • 0
    I

    Inspired by a solution I saw in another question that asked us to implement Stack using Queue...

        Stack<Integer> stack = new Stack<>();
    	
        // Push element x to the back of queue.
        public void push(int x) {
            Stack<Integer> temp = new Stack<>();
            temp.add(x);
            temp.addAll(stack);
            stack = temp;
        }
    
        // Removes the element from in front of queue.
        public void pop() {
            stack.pop();
        }
    
        // Get the front element.
        public int peek() {
        	return stack.peek();
        }
    
        // Return whether the queue is empty.
        public boolean empty() {
            return stack.isEmpty();
        }
    

    ... seems to me like it's the exact same logic as the other question: to reverse the order in which elements are pushed. Then everything else works out.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.