题解 | #【模板】栈#

【模板】栈

http://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf

Java语言 采用数组实现 粗略注释


import java.util.*;

public class Main {
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = Integer.valueOf(scanner.nextLine());
        MyStack stk = new MyStack(n);
        // 循环读取操作
        while(n-- > 0) {
            String[] cmd = scanner.nextLine().split(" ");
            if("push".equals(cmd[0])) {
                int num = Integer.valueOf(cmd[1]);
                stk.push(num);
            }else if("top".equals(cmd[0])) {
                // 根据栈是否为空来输出“error”
                if(stk.isEmpty()) {
                   System.out.println("error"); 
                }else {
                    System.out.println(stk.top());
                }
            }else if("pop".equals(cmd[0])) {
                if(stk.isEmpty()) {
                   System.out.println("error"); 
                }else {
                    System.out.println(stk.pop());
                }
            }
        }
    }
}

class MyStack {
    
    // 存放数据
    private int[] nums;
    // 栈顶指针,指向栈顶元素的上面一格
    private int top;
    
    public MyStack() {
        nums = new int[100000];
        top = 0;
    }
    
    public MyStack(int n) {
        nums = new int[n];
        top = 0;
    }
    
    public void push(int num) {
        nums[top++] = num;
    }
    
    public int pop() {
        if(top < 1) {
            return -1;
        }
        int res = nums[--top];
        return res;
    }
    
    public int top() {
        if(top == 0) {
            return -1;
        }
        return nums[top-1];
    }
    
    public boolean isEmpty() {
        return top < 1;
    }
}
全部评论

相关推荐

点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

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