代码随想录算法训练营第十天| 232.用栈实现队列、225. 用队列实现栈

java语言实现栈、队列、双端队列总结

  • LinkedList实现了DequeQueue接口,栈、队列、双端队列都用new LinkedList<>();来创建
  • Java中有Stack类用于表示栈,但这个类已经过时了。官方文档推荐用Deque来实现栈
Queue<> queue = new LinkedList<>(); //队列
Deque<> deque = new LinkedList<>();//双端队列
Deque<> stack = new LinkedList<>();//栈

队列

boolean offer(E):在队尾添加元素,添加成功返回true,如果队列已满添加失败则返回false。
E poll():删除队头元素,并返回删除的元素,如果队列为null,返回null。
E peek():获取队头元素,如果队列为空将返回null。
Boolean isEmpty(): 判断队列是否为空,如果为空则返回true,否则返回null
int size():返回元素个数

双端队列

boolean offerFirst(E):在队头添加元素,并返回是否添加成功。
boolean offerLast(E):在队尾添加元素,并返回是否添加成功。
E pollFirst():删除队头元素,并返回删除的元素,如果队列为空,返回null。
E pollLast():删除队尾元素,并返回删除的元素,如果队列为空,返回null。
E peekFirst():获取队头元素,如果队列为空将返回null。
E peekLast():获取队尾元素,如果队列为空将返回null。
Boolean isEmpty(): 判断队列是否为空,如果为空则返回true,否则返回null
int size():返回元素个数

E peek():获取队头元素,如果队列为空将返回null。
void push(E):栈顶添加一个元素。
E pop():移除栈顶元素,返回移除的元素,如果栈没有元素抛出异常。
Boolean isEmpty(): 判断队列是否为空,如果为空则返回true,否则返回null
int size():返回元素个数

232.用栈实现队列

题目链接:232.用栈实现队列

class MyQueue {
    Deque<Integer> inStack;
    Deque<Integer> outStack;
    public MyQueue() {
        inStack = new LinkedList<>();
        outStack = new LinkedList<>();
    }
    
    public void push(int x) {
        inStack.push(x);
    }
    
    public int pop() {
        if (outStack.isEmpty()) {
            inToOut();
        }
        return outStack.pop();
    }
    
    public int peek() {
        if (outStack.isEmpty()) {
            inToOut();
        }
        return outStack.peek();
    }
    
    public boolean empty() {
        return inStack.isEmpty() && outStack.isEmpty();
    }
    private void inToOut() {
        while (!inStack.isEmpty()) {
            outStack.push(inStack.pop());
        }
    }
}

225. 用队列实现栈

题目链接:225. 用队列实现栈
单队列实现模拟栈,核心思想,每添加一个元素,将其他元素移到队列后

class MyStack {
    Queue<Integer> queue;

    public MyStack() {
        queue = new LinkedList<>();
    }
    
    public void push(int x) {
        queue.offer(x);
        int size = queue.size();
        while (size-- > 1) {
            queue.offer(queue.poll());
        }
    }
    
    public int pop() {
        return queue.poll();
    }
    
    public int top() {
        return queue.peek();
    }
    
    public boolean empty() {
        return queue.isEmpty();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值