使用链表进行模拟栈比用数组好用,考虑的要素也少还方便。
链表结构
private class Node{//链表结构Item item;Node next;}
迭代器
private class Iterator implements java.util.Iterator<Item>{//迭代器private Node p=first;@Overridepublic boolean hasNext() {return p!=null;}@Overridepublic Item next() {Item item=p.item;p=p.next;return item;}@Overridepublic void remove() {}}
完整源代码
static class stack<Item>{private Node first;private int N;private class Node{//链表结构Item item;Node next;}private int size(){return N;}private boolean isEmpty(){return first==null;}private void push(Item item){//入栈Node oldfirest=first;first=new Node();first.item=item;first.next=oldfirest;N++;}private Item pop(){//出栈Item item=first.item;first=first.next;N--;return item;}private Iterator iterator(){return new Iterator();}private class Iterator implements java.util.Iterator<Item>{//迭代器private Node p=first;@Overridepublic boolean hasNext() {return p!=null;}@Overridepublic Item next() {Item item=p.item;p=p.next;return item;}@Overridepublic void remove() {}}}
简单的使用
static public void main(String[] args) {stack<String> stack = new stack<String>();System.out.println("入栈中... ...");stack.push("hello world!");stack.push("hello Java!");stack.push("hello stack");System.out.println("--------出栈---------");String pop = stack.pop();System.out.println(pop);System.out.println("--------迭代--------");ListStack.stack<String>.Iterator iterator = stack.iterator();while(iterator.hasNext()){System.out.println(iterator.next());}