import java.util.Arrays;//用数组实现栈数据结构publicclassMyStack<E>{private Object[] stack;privateint size;// 数组中存储元素的个数publicMyStack(){
stack =newObject[10];// 初始长度为10}// 判断栈是否为空publicbooleanisEmpty(){return size ==0;}public E peek(){if(isEmpty()){return null;}else{return(E) stack[size -1];}}public E pop(){
E e =peek();if(e == null){
System.out.println("栈中已经没有元素了!!");return null;}
stack[size -1]= null;
size--;return e;}public E push(E item){ensureCapacity(size +1);
stack[size++]= item;//很有意思的一行代码J:size +1 了,数据存在下标为size的位置上。return item;}publicvoidensureCapacity(int size){int len = stack.length;if(size > len){int newLen =10;
stack = Arrays.copyOf(stack, newLen);}}}
用链表来实现栈的数据结构
publicclassNode<E>{
E data;
Node next;publicNode(E data){this.data = data;}}
publicclassStack<E>{
Node<E> top = null;publicbooleanisEmpty(){return top == null;}publicvoidpush(E data){
Node<E> tmp =newNode<E>(data);
tmp.next = top;
top = tmp;}public E pop(){if(isEmpty()){return null;}
E data = top.data;
top = top.next;return data;}public E peek(){if(isEmpty()){return null;}return top.data;}}