栈
链表实现
java">public class MYStack <E> implements Iterable<E>{private int size=0;private int capacity = Integer.MAX_VALUE;private Node<E> head;@Overridepublic Iterator<E> iterator() {return new Iterator<E>() {Node<E> p = head.next;@Overridepublic boolean hasNext() {return p!=null;}@Overridepublic E next() {E val = p.val;p= p.next;return val;}};}private static class Node<E>{E val;Node<E> next;public Node(E val, Node<E> next) {this.val = val;this.next = next;}}public MYStack(int capacity) {head=new Node<>(null,null);this.capacity = capacity;}public MYStack() {head=new Node<>(null,null);}public boolean push(E val){if (isFull())return false;head.next = new Node<>(val, head.next);size++;return true;}public E pop(){if (isEmpty()) return null;Node<E> top = head.next;head.next=top.next;size--;return top.val;}public E peek(){if (isEmpty())return null;return head.next.val;}public boolean isEmpty(){return size==0;}public boolean isFull(){return size == capacity;}
}
数组实现
java">
public class MYStack2<E> implements Iterable<E>{private E[] array;private int top;private int capacity = 10;public MYStack2(int capacity) {this.capacity = capacity;array = (E[]) new Object[capacity];}public MYStack2() {array = (E[]) new Object[capacity];}@Overridepublic Iterator<E> iterator() {return new Iterator<E>() {int p = top;@Overridepublic boolean hasNext() {return p>0;}@Overridepublic E next() {return array[--p];}};}public boolean push(E val){if (isFull())return false;array[top++]=val;return true;}public E pop(){if (isEmpty()) return null;return array[top--];}public E peek(){if (isEmpty())return null;return array[top];}public boolean isEmpty(){return top==0;}public boolean isFull(){return top == capacity;}
}