两个栈实现队列

用两个栈来实现一个队列,完成队列的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){//如果第二个栈为空才往里面push;
        while(!stack1.isEmpty()){
            stack2.push(stack1.pop());

        }}
        int head = stack2.pop();
//         while(!stack2.isEmpty()){
//             stack1.push(stack2.pop());
//         }//我的方法在连续pop时将很浪费时间;
        return head;
    }
}

括号匹配

给出一个仅包含字符'(',')','{','}','['和']',的字符串,判断给出的字符串是否是合法的括号序列
括号必须以正确的顺序关闭,"()"和"()[]{}"都是合法的括号序列,但"(]"和"([)]"不合法。

import java.util.*;
import java.util.Stack;
public class Solution {
    /**
     * 
     * @param s string字符串 
     * @return bool布尔型
     */
    public boolean isValid (String s) {
        // write code here
        Stack<Character> c = new Stack<Character>();
        for(int i = 0 ; i < s.length(); i++){
            if(c.empty()){//为空就入栈
                c.push(s.charAt(i));
                continue;
            }//否则比较栈顶。匹配才出栈
            if(s.charAt(i)==')'&&c.peek()=='('){c.pop();}
            else if(s.charAt(i)=='}'&&c.peek()=='{'){c.pop();}
            else if(s.charAt(i)==']'&&c.peek()=='['){c.pop();}
            else{ c.push(s.charAt(i));}//不为空要入栈时在最后处理
        }
        return c.empty();
    }
}
全部评论

相关推荐

06-11 17:39
门头沟学院 Java
小呆呆的大鼻涕:卧槽,用户彻底怒了
点赞 评论 收藏
分享
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-07 12:04
毕业生招你惹你了,问一个发薪日来一句别看网上乱七八糟的你看哪个工作没有固定发薪日扭头就取消了面试就问了一句公司都是这个态度吗还搞上人身攻击了...
程序员小白条:呃呃呃,都还没面试,我都不会问这么细,何况通不通过,去不去都另说,你没实力和学历的话,在外面就这样,说实话没直接已读不回就不错了,浪费时间基本上
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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