剑指Offer第五题:用两个栈实现队列

用两个栈实现队列

https://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6?tpId=13&tqId=11158&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

题目:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

解答:
别人家的解答:
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.push(node);
}

public int pop() {
    if (stack2.size() <= 0) {
        while (stack1.size() != 0) {
            stack2.push(stack1.pop());
        }
    }
    return stack2.pop();
}

}

我的解答:(写繁琐了,问题出在每次进出不是必须要交换两个栈的数据的,贴上以示警告)
public class Q_5 {

Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
boolean isUse=false;

public void push(int node) {
    while(isUse){
        System.out.println("using");
    }
    isUse=true;
    if(!stack2.isEmpty()){
        stack1.empty();
        while (!stack2.isEmpty()){
            stack1.push(stack2.pop());
        }
    }
    stack1.push(node);
    isUse=false;
}

public int pop() {
    while(isUse){
        System.out.println("using");
    }
    isUse=true;
    if(!stack1.isEmpty()){
        stack2.empty();
        while(!stack1.isEmpty()){
            stack2.push(stack1.pop());
        }
    }
    int result=stack2.pop();
    isUse=false;
    return  result;
}

public static void main(String[] args) {
    Q_5 test=new Q_5();
    test.push(1);
    test.push(2);
    test.push(3);
    test.push(4);
    System.out.println(test.pop());
    System.out.println(test.pop());
    System.out.println(test.pop());
    System.out.println(test.pop());
}

}

全部评论

相关推荐

昨天 16:38
中南大学 营销
点赞 评论 收藏
分享
09-01 10:50
已编辑
东华大学 C++
PDD校招_内推:拼多多意向和开奖一般都比较晚,可能10月11月才出意向
点赞 评论 收藏
分享
评论
1
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务