力扣简232 用栈实现队列
其实同225题的感觉 一个是用栈实现队列 一个是用队列实现栈
栈队列等的定义,一不用就忘,我无语!而且栈用push和pop,用别的会搞乱!

1 class MyQueue { 2 3 Deque<Integer> stack1; 4 Deque<Integer> stack2; 5 6 public MyQueue() { 7 stack1=new LinkedList<Integer>(); 8 stack2=new LinkedList<Integer>(); 9 } 10 11 public void push(int x) { 12 while(!stack1.isEmpty()) { 13 stack2.push(stack1.poll()); 14 } 15 stack1.push(x); 16 while(!stack2.isEmpty()) { 17 stack1.push(stack2.poll()); 18 } 19 } 20 21 public int pop() { 22 return(stack1.pop()); 23 } 24 25 public int peek() { 26 return(stack1.peek()); 27 } 28 29 public boolean empty() { 30 return stack1.isEmpty(); 31 } 32 }
//看了一眼题解2:通过出栈来分摊入栈的时间复杂度。 明天再写吧
//还有用front来标记队列头的元素 取队列头元素简单 2022 0603补充

1 class MyQueue { 2 3 Deque<Integer> stack1; 4 Deque<Integer> stack2; 5 int flag; 6 7 public MyQueue() { 8 9 stack1=new LinkedList<Integer>(); 10 stack2=new LinkedList<Integer>(); 11 } 12 13 public void push(int x) { 14 if(stack1.isEmpty()) { 15 // stack1.push(x); 16 flag=x; 17 } 18 stack1.push(x); 19 } 20 21 public int pop() { 22 if(!stack2.isEmpty()) 23 return stack2.pop(); 24 while(!stack1.isEmpty()) { 25 stack2.push(stack1.pop()); 26 } 27 return stack2.pop(); 28 } 29 30 public int peek() { 31 if(!stack2.isEmpty()) { 32 return stack2.peek(); 33 } 34 return flag; 35 } 36 37 public boolean empty() { 38 return stack1.isEmpty()&&stack2.isEmpty(); 39 } 40 }

浙公网安备 33010602011771号