一 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)
来源:CSDN
作者:cakincqm
链接:https://blog.csdn.net/chengqiuming/article/details/104224579