棧模擬佇列
阿新 • • 發佈:2018-11-25
import java.util.Stack; /** * 用兩個棧來實現一個佇列,完成佇列的Push和Pop操作。 佇列中的元素為int型別。 * 棧:push/pop後進先出 * 佇列:push/pop先進先出 * stack:123 * 新增:456 * 輸出:123456 * 意思是,向一個棧中新增node元素後,按佇列的先進先出方式彈出該棧的元素 * @author Administrator * */ public class _棧模擬佇列 { public static void main(String[] args) { /*LinkedList<Object> list = new LinkedList<>(); Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); stack1.push(1); stack1.push(2); stack1.push(3); System.out.println("stack1:"+stack1); stack2.push(4); stack2.push(5); stack2.push(6); System.out.println("stack2:"+stack2); System.out.println("------------------"); while(!stack2.isEmpty()){ stack2.pop(); } stack1.push(4); stack1.push(5); stack1.push(6); System.out.println("stack1:"+stack1); System.out.println("stack2:"+stack2); System.out.println("---------------"); while(!stack1.isEmpty()){ stack2.push(stack1.pop()); } while(!stack2.isEmpty()){ list.add(stack2.pop()); } System.out.println(list);*/ } Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); public void push(int node) { //向棧1新增元素 stack1.push(node); } public int pop() { //將棧2清空 while(!stack2.isEmpty()){ stack2.pop(); } //將棧1元素逆序到棧2 while(!stack1.isEmpty()){ stack2.push(stack1.pop()); } return stack2.pop(); } }