This article mainly introduces Java programming to use two stacks to realize queue code sharing. It has certain reference value. I will share it with you here for friends who need it.
Title: 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.
Classic questions, not much to say, just go to the code
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() { while(!stack1.isEmpty()){ stack2.push(stack1.pop()); } int pop = stack2.pop(); while(!stack2.isEmpty()){ stack1.push(stack2.pop()); } return pop; } }
Summary
The above is the detailed content of A case study of how Java uses two stacks to implement a queue. For more information, please follow other related articles on the PHP Chinese website!