//下压(LIFO)栈(能够动态调整数组大小的实现)
/*
* 每项操作的用时都与集合大小无关
* 空间需求总是不超过集合大小乘以一个常数
*/
package Algorithms;
import java.util.Iterator;
import java.util.NoSuchElementException;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
public class P88_ResizingArrayStack<Item> implements Iterable<Item>{
private Item[] a;
private int n;
public P88_ResizingArrayStack(){
a = (Item[]) new Object[2];
n = 0;
}
public boolean isEmpty(){
return n == 0;
}
public int size(){
return n;
}
private void resize(int capacity){
assert capacity >= n;
//将栈移动到一个大小capacity的新数组
Item[] temp = (Item[]) new Object[capacity];
for (int i = 0; i < n; i++){
temp[i] = a[i];
}
a = temp;
}
//将元素添加到栈顶
public void push(Item item){
if (n == a.length){
resize(2 * a.length);
a[n++] = item;
}
}
//从栈顶删除元素
public Item pop(){
if (isEmpty()){
throw new NoSuchElementException("Stack underflow");
}
Item item = a[n - 1];
a[n - 1] = null; //避免对象游离
n--;
if(n > 0 && n == a.length / 4){
resize(a.length / 2);
}
return item;
}
public Item peek(){
if (isEmpty()){
throw new NoSuchElementException("Stack underflow");
}
return a[n - 1];
}
public Iterator<Item> iterator(){
return new ReverseArrayIterator();
}
//支持后进先出的迭代
private class ReverseArrayIterator implements Iterator<Item>{
private int i;
public ReverseArrayIterator(){
i = n - 1;
}
public boolean hasNext() {
return i >= 0;
}
public void remove() {
throw new UnsupportedOperationException();
}
public Item next() {
if (!hasNext()) throw new NoSuchElementException();
return a[i--];
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
P88_ResizingArrayStack<String> stack = new P88_ResizingArrayStack<String>();
while (!StdIn.isEmpty()){
String item = StdIn.readString();
if (!item.equals("-")){
stack.push(item);
}
else if (!stack.isEmpty()){
StdOut.print(stack.pop() + " ");
}
}
StdOut.println("(" + stack.size() + " left on stack)");
}
}
下压(LIFO)栈(能够动态调整数组大小的实现)
最新推荐文章于 2021-02-21 07:21:59 发布