剑指offer--队列、栈(2)

2020-03-14  本文已影响0人  机智的柠檬

参考:https://www.cnblogs.com/qmillet/p/12016285.html
知识点 : Stack API

image.png

题目一:
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
方法一:
暴力解法:
一个栈存储push的数据,一个栈pop数据。每次push前将stack2中数据添加到stack1中,再讲数据存储到stack1中;每次pop数据前将stack1中数据push到stack2中,再返回stack2中的栈顶元素。

import java.util.Stack;

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    
    public void push(int node) {
        while(!stack2.empty()){
            stack1.push(stack2.pop());
        }
        stack1.push(node);
    }
    
    public int pop() {
        while(!stack1.empty()){
            stack2.push(stack1.pop());
        }
        return stack2.pop();
    }
}

方法二:
分析


image.png

push()直接添加到stack1中
pop():当stack2中元素不为空时,直接pop()出stack2栈顶元素,当stack2中元素为空时,将stack1中的所有元素添加到stack2中,再返回stack2中的元素即可

import java.util.Stack;

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    
    public void push(int node) {
        stack1.add(node);
    }
    
    public int pop() {
        if (stack2.size() <= 0) {
            while (stack1.size() != 0) {
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }
}
上一篇 下一篇

猜你喜欢

热点阅读