Sword refers to the second question stack and queue of offer

Stack and queue

Title description

Use two stacks to implement a queue and complete the Push and Pop operations of the queue. The elements in the queue are of type int.

Method one uses c++

class Solution
{
    
    
public:
    void push(int node) {
    
    
        stack1.push(node);
    }

    int pop() {
    
    
        if(stack2.empty()){
    
    
            while(!stack1.empty()){
    
    
                stack2.push(stack1.top());
                stack1.pop();
            }
        }
         int ret = stack2.top();
        stack2.pop();
        return ret;
    }

private:
    stack<int> stack1;
    stack<int> stack2;
};

Method two use java

import java.util.Stack;

public class Solution {
    
    
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    
    public void push(int node) {
    
    
        stack1.push(node);
    }
    
    public int pop() {
    
    
        if(stack1.empty()&&stack2.empty()){
    
    
            throw new RuntimeException("Queue is empty!");
        }
        if(stack2.empty()){
    
    
            while(!stack1.empty()){
    
    
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }
}

Guess you like

Origin blog.csdn.net/as1490047935/article/details/110245258