【代码训练营】day10 | 232.用栈实现队列 & 225. 用队列实现栈

所用代码 java

用栈实现队列 LeecCode 232

题目链接:用栈实现队列 LeecCode 232 - 简单

思路

使用两个栈,一个stack负责放数据,一个stack负责取数据

Stack<Integer> stackPut;
Stack<Integer> stackGet;

public MyQueue() {
    stackPut = new Stack<>();
    stackGet = new Stack<>();
}

public void push(int x) {
    stackPut.push(x);
}

public int pop() {
    PutToGet();
    return stackGet.pop();
}

public int peek() {
    PutToGet();
    return stackGet.peek();
}

public boolean empty() {
    if (stackGet.empty() && stackPut.empty()){
        return true;
    }else {
        return false;
    }
}

public void PutToGet(){
    // 如果stackGet为空,就不用往stackGet里放数据
    if (!stackGet.isEmpty()) return;
    while (!stackPut.empty()){
        // 否则把stackPut的所有元素存到stackGet
        stackGet.push(stackPut.pop());
    }
}

总结

关键在于PutToGet()函数,只有在stack2不为空的时候再往里放数据,否则就和普通的栈没区别了。

用队列实现栈 LeetCode 225

题目链接:用队列实现栈 LeetCode 225 - 简单

思路

单向链表

    Queue<Integer> queue;
    Queue<Integer> temp;

    public MyStack() {
        queue = new LinkedList<>();
        temp = new LinkedList<>();
    }

    public void push(int x) {
        queue.offer(x);
    }

    public int pop() {
        adjust();
        return queue.poll();
    }

    public int top() {
        adjust();
        int top = queue.peek();
        temp.offer(queue.poll());
        queue.offer(temp.poll());
        return top;

    }

    public boolean empty() {
        return 0 == queue.size();
    }

    // 用于调整到链表最后一个元素处于起始位置
    public void adjust(){
        int size = queue.size();
        if (size == 0) return;
        for (int i = 0; i < size - 1; i++) {
            // temp 用来临时接受queue弹出的值
            temp.offer(queue.poll());
            // queue把弹出的值放在队列尾部
            queue.offer(temp.poll());
        }
    }

双向链表

// 用双向链表太简单了
Deque<Integer> deque;

public MyStack() {
   deque = new ArrayDeque<>();
}

public void push(int x) {
   deque.offerLast(x);
}

public int pop() {
   return deque.pollLast();
}

public int top() {
   return deque.peekLast();

}

public boolean empty() {
   return 0 == deque.size();
}

总结

可以看到双向链表操作非常的简单,所有在java里面都不太愿意直接使用Stack了,因为双向链表就可以直接模拟和队列。


ps:今天的题比较简单,只要熟悉栈和队列的基本操作都能做!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值