链表方式实现栈
public class StackImpl<Item> implements Iterable<Item> { private Node first; private int N; /** * 内部类实现链表节点定义 * @author feng * */ private class Node{ Item item; Node next; } public boolean isEmpty(){ return first == null; } public int size(){ return N; } public void push(Item item){ Node oldFirst = first; first = new Node(); first.item = item; first.next = oldFirst; N++; } public Item pop(){ Item item = first.item; first = first.next; N--; return item; } /** * 迭代器 * @author feng * */ @Override public Iterator<Item> iterator() { return new ListIterator(); } /** * 内部类实现迭代器 * @author feng * */ private class ListIterator implements Iterator<Item>{ private Node current = first; @Override public boolean hasNext() { // TODO Auto-generated method stub return current != null; } public void remove(){} @Override public Item next() { Item item = current.item; current = current.next; return item; } } }
链表方式实现队列
public class QueueImpl<Item> implements Iterable<Item> { private Node first; private Node last; private int N; private class Node{ Item item; Node next; } public boolean isEmpty(){ return first == null; } public int size(){ return N; } public void enqueue(Item item){ Node oldlast = last; last.item = item; last.next = null; if(isEmpty()){ first = last; }else{ oldlast.next = last; } N++; } public Item dequeue(){ Item item = first.item; first = first.next; if(isEmpty()){ last = null; } N--; return item; } /** * 迭代器 */ @Override public Iterator<Item> iterator() { // TODO Auto-generated method stub return new ListIterator(); } /** * 迭代器实现类 * @author feng * */ private class ListIterator implements Iterator<Item>{ private Node current = first; @Override public boolean hasNext() { // TODO Auto-generated method stub return current != null; } public void remove(){} @Override public Item next() { Item item = current.item; current = current.next; return item; } } }