1. 程式人生 > >兩個棧實現一個佇列(java)

兩個棧實現一個佇列(java)

一、問題描述

使用兩個棧實現一個佇列

二、演算法分析

棧是先進後出,因此兩個可以模擬實現先進先出

三、演算法設計

定義資料結構

Stack<Integer> stack1

Stack<Integer> stack2

對於push操作:元素入佇列時,將其加入到stack1中

對於pop操作:元素出佇列時,先判斷stack2是否為空,若不為空,則從stack2中彈出一個元素;若為空,則將stack1中的所有元素彈出到stack2中,然後彈出一個元素

四、程式碼實現

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.isEmpty()&&stack2.isEmpty()){
		   System.out.println("Queue is empty.");
	   }
	   if(stack2.isEmpty()){
		   while(!stack1.isEmpty()){
			   stack2.push(stack1.pop());
		   }
	   }
	   return stack2.pop();
   }
   public static void main(String[] args) {
	   Solution queue = new Solution();
	   queue.push(1);
	   queue.push(2);
	   queue.push(3);
	   System.out.println(queue.pop());
	   queue.push(4);
	   System.out.println(queue.pop());
	   System.out.println(queue.pop());
	   System.out.println(queue.pop());
   }
}