使用链表的方式实现栈
package algorithm_01;
import java.util.Iterator;
public class Stack<T> implements Iterable<T> {
private Node first;
private int N;
private class Node {
T item;
Node next;
}
public boolean isEmpty() {
return first == null;
}
public int size() {
return N;
}
public void push(T item) {
Node oldFirst = first;
first = new Node();
first.item = item;
first.next = oldFirst;
N++;
}
public T pop() {
T item = first.item;
first = first.next;
N--;
return item;
}
@Override
public Iterator<T> iterator() {
return new ReverseArrayIterator();
}
private class ReverseArrayIterator implements Iterator<T> {
private Node current = first;
@Override
public boolean hasNext() {
return current != null;
}
@Override
public T next() {
T item = current.item;
current = current.next;
return item;
}
@Override
public void remove() {
}
}
public static void main(String[] args) {
Stack<String> stack = new Stack<>();
stack.push("aaa");
stack.push("bbb");
stack.push("ccc");
Iterator<String> iterator = stack.iterator();
System.out.println(iterator.hasNext());
System.out.println(iterator.next());
System.out.println(iterator.next());
}
}
使用链表的方式实现队列
package algorithm_01;
import java.util.Iterator;
public class Queue<T> implements Iterable<T> {
private int N;
private Node last;
private Node first;
private class Node {
T item;
Node next;
}
private boolean isEmpty() {
return first == null;
}
private int size() {
return N;
}
private void enqueue(T item) {
Node oldLast = last;
last = new Node();
last.item = item;
last.next = null;
if (isEmpty()) {
first = last;
} else {
oldLast.next = last;
}
N++;
}
private T dequeue() {
T item = first.item;
first = first.next;
if (isEmpty()) {
last = null;
}
N--;
return item;
}
@Override
public Iterator<T> iterator() {
return new QueueIterator();
}
private class QueueIterator implements Iterator<T> {
private Node current = first;
@Override
public boolean hasNext() {
return current != null;
}
@Override
public T next() {
T item = current.item;
current = current.next;
return item;
}
}
public static void main(String[] args) {
Queue<String> queue = new Queue<>();
queue.enqueue("aaa");
queue.enqueue("bbb");
queue.enqueue("ccc");
Iterator<String> iterator = queue.iterator();
System.out.println(iterator.next());
System.out.println(iterator.next());
System.out.println(iterator.next());
System.out.println(iterator.hasNext());
}
}