美文网首页
Java 用两个栈实现队列,两个队列实现栈

Java 用两个栈实现队列,两个队列实现栈

作者: ccccmatser | 来源:发表于2017-11-20 20:52 被阅读9次

栈(stack)又名堆栈,它是一种运算受限的线性表。其限制是仅允许在表的一端进行插入和删除运算。这一端被称为栈顶,相对地,把另一端称为栈底。向一个栈插入新元素又称作进栈、入栈或压栈,它是把新元素放到栈顶元素的上面,使之成为新的栈顶元素;从一个栈删除元素又称作出栈或退栈,它是把栈顶元素删除掉,使其相邻的元素成为新的栈顶元素。

队列

队列是一种特殊的线性表,特殊之处在于它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作,和栈一样,队列是一种操作受限制的线性表。进行插入操作的端称为队尾,进行删除操作的端称为队头。

一:用两个栈实现队列

import java.util.Stack;

public class StackToQueue<T> {
    private Stack<T> stack1;
    private Stack<T> stack2;
    
    public StackToQueue(){
        this.stack1 = new Stack<T>();
        this.stack2 = new Stack<T>();
    }
    public T get() {
        if(this.stack2.size() != 0) {
            return this.stack2.pop();
        }else {
            while(this.stack1.size() != 0) {
                this.stack2.push(this.stack1.pop());
            }
            return this.stack2.pop();
        }
    }
    
    public boolean add(T element) {
        this.stack1.push(element);
        return true;
    }
    public int size() {
        return this.stack1.size() + this.stack2.size();
    }
    
}   

二:用两个队列实现栈

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

public class QueueToStack<T> {
    private Queue<T> queue1;
    private Queue<T> queue2;
    
    public QueueToStack() {
        this.queue1 = new LinkedList<T>();
        this.queue2 = new LinkedList<T>();
    }
    
    public boolean push(T element) {
        this.queue1.add(element);
        return true;
    }
    public T pop() {
        if(this.queue1.size() == 1) {
            return this.queue1.poll();
        }else {
            while(this.queue1.size() > 1) {
                this.queue2.add(this.queue1.poll());
            }
            T ans = this.queue1.poll();
            while(this.queue2.size() > 0) {
                this.queue1.add(this.queue2.poll());
            }
            return ans;
        }
    }
    public int size() {
        return this.queue1.size() + this.queue2.size();
    }
}

相关文章

  • 用两个栈实现队列,用两个队列实现堆栈

    参考:剑指Offer面试题7(Java版):用两个栈实现队列与用两个队列实现栈 用两个栈实现队列stack1作为入...

  • 栈&队列

    一、栈&队列总结 栈/队列的应用接雨水验证栈序列滑动窗口的最大值 栈/队列的特殊实现用两个栈实现队列用两个队列实现...

  • 面试题9: 用两个栈实现队列

    9-1 用两个栈实现队列 9-2 用两个队列实现栈

  • 栈和队列

    两个栈实现队列 两个队列实现栈

  • 连个栈实现一个队列

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

  • 手撕栈队列

    【面试题07:用两个栈实现队列】 题目:利用两个栈实现队列的插入,取队首,判断非空等函数。拓展:用两个队列实现栈,...

  • LeetCode 每日一题 [43] 用两个栈实现队列

    LeetCode 用两个栈实现队列 [简单] 用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appen...

  • 剑指offer第二版-9.用两个栈实现队列

    本系列导航:剑指offer(第二版)java实现导航帖 面试题9:用两个栈实现队列 题目要求:用两个栈,实现队列的...

  • 剑指Offer

    09 用两个栈实现队列 用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 del...

  • 总结的笔试/面试算法题

    目录 1. 栈和队列1.用两个队列实现栈2.用两个栈实现队列3.实现一个栈,可以用常数级时间找出栈中的最小值4.判...

网友评论

      本文标题:Java 用两个栈实现队列,两个队列实现栈

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