面试题7. 用两个栈实现队列

来源:互联网 发布:奥登nba那场数据最强 编辑:程序博客网 时间:2024/05/22 00:51

题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

思路:

假设有两个栈stack1,stack2。stack1存储负责入栈的数据,stack2负责存储出栈的数据。

  • 入队列时,向stack1压入数据
  • 出队列时,如果stack2为空,就把stack1中的数据导入到stack2中,然后stack2执行出栈操作
  • 以后再有入栈的数据,依旧压入到stack1中

这里写图片描述

这里写图片描述

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() {        // 如果stack2为空,就把stack1中的数据导入到stack2中        if(stack2.isEmpty()) {             while(!stack1.isEmpty()) {                stack2.push(stack1.pop());            }            }        return stack2.pop();    }}

思考题1、:用两个队列实现栈

  • 入栈时,先把数据存在q1中,比如当前入栈的数据为【1、2、3】
  • 出栈时,由于栈的后进先出特性,3是最后进入栈的,应该最先出栈。我们把q1中的数据【1、2】都导入到q2中,只留下【3】在q1中。然后,执行q1.pop(),把3弹出去。
  • 接下来再有入栈的操作,把数据压入q2中,等到出栈时,再把q2中的数据导入到q1中。

这里写图片描述

这里写图片描述

参考代码:

Queue<Integer> queue1 = new LinkedList();Queue<Integer> queue2 = new LinkedList();public void push(int i) {    if(!queue2.isEmpty()) {        queue2.add(i);    }else {        queue1.add(i);    }}public int pop() {    if(queue1.isEmpty()) {        while(queue2.size() > 1) {            queue1.add(queue2.poll());        }        return queue2.poll();    }else {        while(queue1.size() > 1) {            queue2.add(queue1.poll());        }        return queue1.poll();    }}

注:学渣心里苦,不要学楼主,平时不努力,考试二百五,哭 ~

这里写图片描述