使用栈完成队列功能

小算法
问题概述:
使用栈完成队列先进先出的功能
思路:
使用两个栈,入栈使用A栈,出栈时将A栈中所有元素全部放入B栈中之后再从B栈中取元素就OK

package algorithm;

public class StackQueue {
    MyStack stackA = new MyStack();
    MyStack stackB = new MyStack();
    public static void main(String[] args) {
        StackQueue stackQueue = new StackQueue();
        stackQueue.enqueue(1);
        stackQueue.enqueue(2);
        System.out.println(stackQueue.dequeue());
        System.out.println(stackQueue.dequeue());
        System.out.println(stackQueue.dequeue());
    }
    public void enqueue(Integer element){
        stackA.push(element);
    }
    public Integer dequeue(){
        if (stackB.isEmpty()){
            if (stackA.isEmpty()){
                return null;
            }
            transfer(stackA,stackB);
        }
        return stackB.pop();
    }
    public void transfer(MyStack stackA,MyStack stackB){
        while (!stackA.isEmpty()){
            stackB.push(stackA.pop());
        }
    }
}
class MyStack{
    private class Node{
        Integer element;
        Node next;
        public Node(Integer element, Node next) {
            this.element = element;
            this.next = next;
        }
    }
    public Node stack;
    public int N;
    public void push(Integer element){
        Node NewNode = new Node(element,null);
        NewNode.next = stack.next;
        stack.next = NewNode;
    }

    public Integer pop(){
        Integer element = stack.next.element;
        stack.next = stack.next.next;
        return element;
    }
    public boolean isEmpty(){
        return stack.next==null;
    }

    public MyStack() {
        this.stack = new Node(null,null);
        N = 0;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值