简书 賈小強
转载请注明原创出处,谢谢!
package com.lab1.test1;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class LinkedQueue<Item> implements Iterable<Item> {
private int n;
private Node first, last;
private class Node {
private Item item;
private Node next;
}
@Override
public Iterator<Item> iterator() {
return new ListIterator();
}
private class ListIterator implements Iterator<Item> {
Node current = first;
@Override
public boolean hasNext() {
return current != null;
}
@Override
public Item next() {
Item item = current.item;
current = current.next;
return item;
}
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (Item item : this) {
builder.append(item + " ");
}
return builder.toString();
}
private boolean isEmpty() {
return first == null;
}
private int size() {
return n;
}
private void push(Item item) {
Node oldlast = last;
last = new Node();
last.item = item;
if (isEmpty()) {
first = last;
} else {
oldlast.next = last;
}
n++;
}
private Item pop() {
if (isEmpty()) {
throw new NoSuchElementException("empty stack exception");
}
Item item = first.item;
first = first.next;
if (isEmpty()) {
last = null;
}
n--;
return item;
}
public static void main(String[] args) {
LinkedQueue<String> stack = new LinkedQueue<>();
System.out.println(stack);
System.out.println(stack.size());
System.out.println(stack.isEmpty());
stack.push("bill");
stack.push("jack");
stack.push("lucy");
System.out.println(stack);
System.out.println(stack.size());
System.out.println(stack.isEmpty());
stack.pop();
stack.pop();
System.out.println(stack);
System.out.println(stack.size());
System.out.println(stack.isEmpty());
}
}
输出
0
true
bill jack lucy
3
false
lucy
1
false
Happy learning !!