泛型定容栈抽象数据模型

耗尽温柔 提交于 2020-02-08 16:58:29

一 API

public class FixedCapcityStack<Item>

public FixedCapcityStack( int cap )

创建一个容量为cap的空栈

public void push(Item item)

创建一个字符串

public Item pop()

删除最近添加的字符串

public boolean isEmpty()

栈是否为空

public int size()

栈中字符串数量

二 代码

package FixedCapcityStack;


import common.StdIn;
import common.StdOut;


/**
* Copyright (C), 2020-2020, XXX有限公司
* FileName: FixedCapcityStack
* Author:   cakin
* Date:     2020/2/8
* Description: 泛型定容栈
*/
public class FixedCapcityStack<Item> {
    private Item[] a;
    private int N;


    public FixedCapcityStack( int cap ) {
        a = (Item[])(new Object[cap]);
    }


    public boolean isEmpty(){
        return N == 0;
    }


    public int size(){
        return N;
    }


    public void push(Item item){
        a[N++] =  item;
    }


    public Item pop(){
        return a[--N];
    }


    public static void main( String[] args ) {
        FixedCapcityStack<String> s;
        s = new FixedCapcityStack<String>(100);
        while(!StdIn.isEmpty()){
            String item = StdIn.readString();
            if(!item.equals("-")){
                s.push(item);
            }
            else if(!s.isEmpty()) {
                StdOut.print(s.pop()+" ");
            }
        }
        StdOut.println("("+s.size()+" left on stack)");
    }
}

三 测试

F:\Algorithm\target\classes>more tobe.txt
to be or not to - be - - that - - - is
F:\Algorithm\target\classes>java FixedCapcityStack.FixedCapcityStack < tobe.txt
to be not that or be (2 left on stack)

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!