栈的原则是先进后出,比如一堆摞起来的书,后放上去的会被最先拿到。
栈的特点是每次只允许访问一个元素。
栈是一种抽象出来的数据结构,它的底层存储依赖于数组和链表,下面列出它的两种实现
public interface Stack <T>{ boolean isEmpty(); void clear(); int length(); boolean push(T obj); T pop(); boolean hashNext(); }
public class ArrayStack<T> implements Stack<T> { private static final int DEFULT_SIZE = 20; private static final int STEP_SIZE = 10; private Object[] objects = new Object[DEFULT_SIZE]; private int size; @Override public boolean isEmpty() { return size == 0; } @Override public void clear() { for (int i = 0; i < size; i++) { objects[i] = null; } size = 0; } @Override public int length() { return size; } @Override public boolean push(T obj) { resize(); objects[++size] = obj; return true; } @SuppressWarnings("unchecked") @Override public T pop() { if(size == 0){ return null; } return (T) objects[--size]; } public void resize() { if(size >= objects.length){ Object[] temp = new Object[objects.length + STEP_SIZE]; for(int i=0;i<objects.length;i++){ temp[i] = objects[i]; objects[i] = null; } objects = temp; } } @Override public boolean hashNext() { return objects[size - 1] != null; } public static void main(String[] args) { Stack<Integer> linkedStack = new LinkedStack<Integer>(); linkedStack.push(1); linkedStack.push(2); linkedStack.push(3); linkedStack.push(4); linkedStack.push(5); while(linkedStack.hashNext()){ System.out.println(linkedStack.pop()); } } }
public class LinkedStack<T> implements Stack<T>{ int size = 0; private Item top; private final class Item{ private Item next; private T data; private Item(T data,Item next){ this.data = data; this.next = next; } private boolean hasNext(){ return next != null; } } @Override public boolean isEmpty() { return size == 0; } @Override public void clear() { setItemNull(top); size = 0; } @Override public int length() { return size; } private void setItemNull(Item item){ if(item.hasNext()){ setItemNull(item.next); } item = null; } @Override public boolean push(T obj) { Item item = new Item(obj,top); top = item; size ++; return true; } @Override public T pop() { if(top != null){ Item item = top; top = item.next; size--; return item.data; } return null; } @Override public boolean hashNext() { return top != null; } public static void main(String[] args) { Stack<Integer> linkedStack = new LinkedStack<Integer>(); linkedStack.push(1); linkedStack.push(2); linkedStack.push(3); linkedStack.push(4); linkedStack.push(5); while(linkedStack.hashNext()){ System.out.println(linkedStack.pop()); } } }
原文地址:http://blog.csdn.net/ilovezhangxian/article/details/27186501