剑指offer之面试题7:用两个栈实现队列

题目描述

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

思路:push操作无所谓栈或队列,都是往里面加入元素。而区别在于pop操作,队列的pop操作取的是先push的元素,而栈pop的则是最后push的元素,怎样通过两个栈来实现队列的pop操作,是主要问题所在。举个例子,向stack1中逐个push进a,b,c,则stack1中元素{a,b,c},c位于栈顶,再将stack1中元素pop,并push进stack2中,则stack2元素{c,b,a},a位于栈顶,pop出的顺序为a,b,c,符合先进先出的队列。简而言之,stack2中的元素是符合队列pop顺序的,可以直接pop,而stack1中的元素要想按照队列的pop需先push到stack2中,即当stack2不为空时,可以直接pop,当stack2为空时,将stack1中的元素pop并push进stack2中,再pop。

说的有点乱,贴上代码,就会更容易理解:

import java.util.Stack;

public class Solution {
    public static Stack<Integer> stack1 = new Stack<Integer>();
    public static Stack<Integer> stack2 = new Stack<Integer>();

    public static void push(int node) {
        stack1.push(node);
    }

    public static int pop() {
        if(stack2.empty()){
            while(!stack1.empty()){
                stack2.push(stack1.pop());
            }
        }
        if(stack2.empty()){
            System.out.println("queue is empty");
        }
        return stack2.pop();
    }
    public static void main(String[] args){
        push(1);
        push(2);
        push(3);
        push(4);
        System.out.println(pop());
    }
}

扩展:用两个队列实现一个栈

思路:栈的push操作,当两个队列都为空时,不妨将元素push进queue1;或者push进非空队列。栈的pop操作,根据队列的先进先出原则,先插入的元素在队首,后插入的在队尾,而栈的操作要求后进先出,即队尾的元素要先出,可以将非空队列的元素逐个出队并入队到空队列中,直到空队列剩余一个元素,此时删除这个元素即可。

贴出代码

package com.su.biancheng;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @title StackWithTwoQueues.java
 * @author Shuai
 * @date 2016-4-15下午9:00:25
 */
public class StackWithTwoQueues {
    public static Queue<Integer> queue1=new LinkedList<Integer>();
    public static Queue<Integer> queue2=new LinkedList<Integer>();
    public static void push(int e){
        //插入非空队列
        if(queue2.isEmpty())
            queue1.offer(e);
        if(queue1.isEmpty())
            queue2.offer(e);
    }
    public static int pop(){
        //将非空队列的元素逐个出队并插入到空队列
        //poll,获取并移除此队列的头,如果此队列为空,则返回 null。
        //remove,获取并移除此队列的头。此方法与 poll 唯一的不同在于:此队列为空时将抛出一个异常。
        if(!queue1.isEmpty()){
            while(queue1.size()>1){
                queue2.offer(queue1.poll());
            }
            return queue1.poll();
        }
        else if(!queue2.isEmpty()){
            while(queue2.size()>1){
                queue1.offer(queue2.poll());
            }
            return queue2.poll();
        }
        return 0;

    }
    public static void main(String[] args){
        push(1);
        push(2);
        push(3);
        push(4);
        push(5);
        System.out.println(pop());
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值