题解 | #【模板】栈#

【模板】栈

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

import java.util.Scanner;
//使用一个数组作为栈,初始容量为10
//使用一个int成员变量作为指针,指向栈顶。
//push前先判断栈是否满,若满了,则扩容两倍。
public class Main{
    public static void main(String[] args){
        MyStack stack = new MyStack();
        Scanner scanner = new Scanner(System.in);
        int optNum = scanner.nextInt();
        String line = scanner.nextLine();
        while(optNum>0){
            line = scanner.nextLine();
            if(line.length()>3){
                line = line.substring(5);
                stack.push(Integer.parseInt(line));
            }else{
                if(line.charAt(0) == 't'){
                    stack.top();
                }else{
                    stack.pop();
                }
            }
            optNum--;
        }
    }
    
    
}

class MyStack{
    int arr[];
    int index;
    public MyStack(){
        arr = new int[10];
        index = 0;
    }
    public void push(int x){
        extend();
        arr[index++] = x;
    }
    
    public void pop(){
        if(index == 0){
            System.out.println("error");
        }else{
            System.out.println("" + arr[--index]);
        }
    }
    
    public void top(){
        if(index == 0){
            System.out.println("error");
        }else{
            System.out.println("" + arr[index-1]);
        }
    }
    
    public void extend(){
        if(index == arr.length-1){
            int[] temp = new int[arr.length*2];
            for(int i = 0; i < arr.length; i++){
                temp[i] = arr[i];
            }
            arr = temp;
        }
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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