美文网首页
栈和队列的相互实现

栈和队列的相互实现

作者: 不会游泳的金鱼_ | 来源:发表于2019-08-14 16:58 被阅读0次

两个栈实现队列:

一个栈用来入,一个栈用来出

public class StackToQueue<T> {
    private Stack<T> stackin;
    private Stack<T> stackout;
    
    public StackToQueue() {
        stackin = new Stack<T>();
        stackout = new Stack<T>();
    }
    
    public void add(T a) {
        stackin.add(a);
    }
    
    public T poll() {
        if(stackout.isEmpty()) {
            while(!stackin.isEmpty()) {
                stackout.add(stackin.pop());
            }   
        }
        if (stackout.isEmpty()) {  
            throw new RuntimeException("No more element.");  
        }  
        return stackout.pop();

    }
    
}

两个队列实现栈:

入栈的时候正常存入一个队列,出栈的时候用另一个队列保存除最后一个元素以外的元素,并将最后一个元素出队。

public class QueueToStack<T> {
    Queue<T> queueA;
    Queue<T> queueB;
    Boolean isA;
    
    public QueueToStack() {
        queueA = new LinkedList<>();
        queueB = new LinkedList<>();
        isA = true;
    }
    
    public void push(T a) {
        if(isA) {
            queueA.offer(a);
        }else {
            queueB.offer(a);
        }
    }
    
    public T pop() {
        if(isA) {
            int size = queueA.size();
            for(int i = 0; i < size - 1; i++) {
                queueB.offer(queueA.poll());
            }
            isA = false;
            return queueA.poll();
        }else {
            int size = queueB.size();
            for(int i = 0; i < size - 1; i++) {
                queueA.offer(queueB.poll());
            }
            isA = true;
            return queueB.poll();
        }
    }

}

相关文章

网友评论

      本文标题:栈和队列的相互实现

      本文链接:https://www.haomeiwen.com/subject/naknjctx.html