两个栈形成队列

数据入第一个栈,再从第一个栈进入第二个栈,从第二个栈弹出时即是队列。

代码实现:

package datastruct;

import java.util.*;

public class Demo1 {
	public static void main(String []args) {
		Stack stack1 = new Stack();
		Stack stack2 = new Stack();
		stack1.push(1);
		stack1.push(2);
		stack1.push(3);
		stack1.push(4);
		while(!stack1.isEmpty()) {
			//System.out.println(stack1.pop());
			stack2.push(stack1.pop());
		}
		while(!stack2.isEmpty()) {
			System.out.println(stack2.pop());
		}
	}
}

 

你可能感兴趣的:(算法)