题解 | #用递归函数和栈逆序一个栈#
用递归函数和栈逆序一个栈
http://www.nowcoder.com/practice/1de82c89cc0e43e9aa6ee8243f4dbefd
import java.util.Deque; import java.util.Scanner; import java.util.LinkedList; public class Main{ public static void main(String[] args) { myQueue myque = new myQueue(); Scanner sc = new Scanner(System.in); int length = Integer.parseInt(sc.nextLine()); for(int i=0; i<length; i++) { String[] str = sc.nextLine().split(" "); if(str[0].equals("add")) { myque.add(Integer.parseInt(str[1])); } if(str[0].equals("peek")) { int num = myque.peek(); System.out.println(num); } if(str[0].equals("poll")) { myque.poll(); } } } } class myQueue{ Deque<Integer> deque = null; Deque<Integer> deque_bgk = null; int top = 0; //栈顶元素 public myQueue(){ deque = new LinkedList<>(); deque_bgk = new LinkedList<>(); } public void add(int num){ if(deque.isEmpty()) { top = num; } deque.push(num); } public int peek(){ return top; } public void poll(){ int size = deque.size(); while(--size>0){ deque_bgk.push(deque.poll()); } deque.poll(); if(!deque_bgk.isEmpty()) top = deque_bgk.peek(); else top = 0; while(!deque_bgk.isEmpty()){ deque.push(deque_bgk.poll()); } } }