[Java common interview questions] use two stacks to achieve queue entry and exit

This is a common interview question. It is actually very simple. The queue is first-in first-out, and the stack is first-in-last-out. After entering the stack twice, it will become a first-in-first-out. But pay attention to the conditions of the stack.

simulation:

Suppose we have two stacks s1 and s2. For enqueue operations, we only need to push the data to s1. When dequeuing operations, we need to push the data of s1 to s2, but we must ensure the data consistency , That is to say, when dequeuing, either the s2 stack is empty, we import all the data of s1 into s2, or the s2 stack is not empty, we don’t have any operations on s1, and we can proceed only after s2 is completely dequeued.

s2 stack empty operation.

Let's look at the entire operation process in combination with the code:

package zhgyu.stack;

import java.util.Stack;

/**
 * 两个stack实现队列的push与pop
 * @author zhgyu
 *
 */
public class StackDemo1 {

	Stack<Integer> s1 = new Stack<>();
	Stack<Integer> s2 = new Stack<>();
	
	public void push(int a) {
		s1.push(a);
	}
	
	public int pop() {
		if(s2.isEmpty()) {    //s2空的时候才可以从s1导入入队的数据
			while(!s1.isEmpty()) {    
				s2.push(s1.pop());
			}
		}
		return s2.pop();    //s2不为空的时候先将s2里的内容出队完
		
	}
}

 

Guess you like

Origin blog.csdn.net/qq_40702130/article/details/84289966