public class Stack<E> implements Iterable { private Node<E> head;//头结点 private int Num;//栈中元素个数 //内部类,定义结点 private class Node<E> { private E data;//存储元素数据 private Node<E> next;//结点 //重载构造器 public Node(E data, Node<E> next) { this.data = data; this.next = next; } } public Stack() { this.head = new Node<>(null, null); } //判断栈是否为空 public boolean isEmpty() { return Num == 0; } //获取栈元素的个数 public int size() { return Num; } //添加元素压入栈 public void push(E e) { //改元素存储到新结点中 Node<E> newNode = new Node<>(e, null); //插入ixn结点到栈 newNode.next = head.next; head.next = newNode; //元素加1 Num++; } //弹出栈顶元素(删除顶栈元素) public E pop() { //找到第一个结点 Node<E> fristnode = head.next; //判断第一个结点是否为null if (fristnode == null) { return null; } else { //让首结点指向的第一个结点 head.next = fristnode.next; Num--; } return fristnode.data; } public String toString() { Node<E> p = head; String ans = ""; while (p.next != null) { p = p.next; ans += p.data + " "; } return ans; } //遍历 @Override public Iterator iterator() { return new SIterator(); } public class SIterator implements Iterator { private Node<E> n;//记录结点 public SIterator() { this.n = head; } @Override public boolean hasNext() { return false; } @Override public Object next() { n = n.next; return n.data; } } } class Test1 { //这是一个main方法,是程序的入口: public static void main(String[] args) { Stack<Integer> l1 = new Stack<>(); l1.push(1); l1.push(2); l1.push(3); l1.push(4); l1.push(5); l1.push(6); for (Object o : l1) { //打印 System.out.println(o); } //打印 //打印 System.out.println("输出所有元素:"+l1.toString()); System.out.println("栈是否为空:"+l1.isEmpty()); System.out.println("弹出栈顶元素:"+l1.pop()); } }