该栈能够动态调整数组,并实现了迭代和泛型。
参考于算法第四版算法1.1
java代码如下:
import java.util.Iterator;
import edu.princeton.cs.algs4.StdIn;
import interfacefile.DataStock;
/**
*
* @author Administrator
*能够动态调整数组的实现了迭代的泛型栈
* @param <Item>
*/
public class ResizingArrayStack<Item> implements DataStock<Item>,Iterable<Item>{
private int N=0;
private Item[] a;
public ResizingArrayStack(int cap) {
// TODO Auto-generated constructor stub
a =(Item[])new Object[cap];
}
public void resize(int max) {
Item[] temp =(Item[]) new Object[max];
for (int i = 0; i < N; i++) {
temp[i]=a[i];
}
a=temp;
}
@Override
public void push(Item item) {
if(N==a.length) resize(a.length*2);
a[N++]=item;
}
@Override
public Item pop() {
Item item=a[--N];
a[N]=null;
if(N>0 && N==a.length/4) resize(a.length/2);
return item;
}
@Override
public boolean isEmpty() {
return N==0;
}
@Override
public int size() {
return N;
}
public int getArrayLength() {
return a.length;
}
//迭代器
@Override
public Iterator<Item> iterator() {
// TODO Auto-generated method stub
return new ReverseArrayIterator();
}
private class ReverseArrayIterator implements Iterator<Item>{
private int i=N;
@Override
public boolean hasNext() {
// TODO Auto-generated method stub
return i>0;
}
@Override
public Item next() {
// TODO Auto-generated method stub
return a[--i];
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ResizingArrayStack<String> stack1;
stack1 =new ResizingArrayStack<String>(10);
int i;
//输入字符串,回车后按ctrl+z结束输入
while(!StdIn.isEmpty()) {
String value= StdIn.readString();
stack1.push(value);
}
System.out.println("original ArrayLength: "+ stack1.getArrayLength());
//遍历当前栈的所有元素并打印(从栈顶开始)
i=stack1.size();
System.out.println("origin:");
for(String temp:stack1) {
System.out.printf("%d:%s ",i--,temp);
}
System.out.println();
//弹出栈顶两个元素,再打印剩下的元素
stack1.pop();
stack1.pop();
i=stack1.size();
System.out.println("after pop ArrayLength: "+ stack1.getArrayLength());
System.out.println("current:");
for(String temp:stack1) {
System.out.printf("%d:%s ",i--,temp);
}
//进栈直到满
for (int j = 0; j < 10; j++) {
stack1.push(j+"");
}
System.out.println();
i=stack1.size();
System.out.println("after push ArrayLength: "+ stack1.getArrayLength());
System.out.println("current:");
for(String temp:stack1) {
System.out.printf("%d:%s ",i--,temp);
}
}
}
测试:
测试我们发现当栈里元素个数为2时,等于原数组长度的1/4,于是调整数组的长度/2,为5,添加元素至栈满时,调整数组长度*2,为20。
网友评论