package tianma.learn.ds.lineartable;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class MyLinkedQueue<E> implements MyQueue<E> {

	private Node<E> front;
	private Node<E> rear;
	private int size;

	private static class Node<E> {
		E element;
		Node<E> next;

		public Node(E element, Node<E> next) {
			this.element = element;
			this.next = next;
		}
	}

	public MyLinkedQueue() {
		front = rear = new Node<E>(null, null);
	}

	@Override
	public Iterator<E> iterator() {
		return new Iter();
	}

	private class Iter implements Iterator<E> {

		private Node<E> curNode;

		public Iter() {
			curNode = front.next;
		}

		@Override
		public boolean hasNext() {
			return curNode != null;
		}

		@Override
		public E next() {
			E value = curNode.element;
			curNode = curNode.next;
			return value;
		}

	}

	@Override
	public void clear() {
		Node<E> tmp = front;
		while (tmp.next != null) {
			Node<E> target = tmp.next;
			tmp.next = target.next;
			target.next = null;
			target.element = null;
			target = null;
		}
		size = 0;
	}

	@Override
	public E element() {
		if (isEmpty()) {
			throw new NoSuchElementException();
		}
		return front.next.element;
	}

	@Override
	public boolean isEmpty() {
		return size == 0;
	}

	@Override
	public boolean offer(E e) {
		// 队尾元素入队
		Node<E> tmp = new Node<E>(e, null);
		rear.next = tmp;
		rear = tmp;
		size++;
		return true;
	}

	@Override
	public E remove() {
		// 队首元素出队
		if (isEmpty()) {
			throw new NoSuchElementException();
		}
		Node<E> tmp = front.next;
		front.next = front.next.next;
		E value = tmp.element;
		tmp.next = null;
		tmp = null;
		size--;
		return value;
	}

	@Override
	public int size() {
		return size;
	}
	
	@Override
	public String toString() {
		Iterator<E> it = iterator();
		if (!it.hasNext())
			return "[]";
		StringBuilder sb = new StringBuilder();
		sb.append('[');
		for (;;) {
			E e = it.next();
			sb.append(e == this ? "(this Collection)" : e);
			if (!it.hasNext())
				return sb.append(']').toString();
			sb.append(',').append(' ');
		}
	}

}

@@ -1667,16 +1667,91 @@
 .next;%0D%0A
+%09%09if (tmp == rear) %7B%0D%0A%09%09%09// %E5%A6%82%E6%9E%9C%E5%AF%B9%E5%A4%B4%E6%98%AF%E9%98%9F%E5%B0%BE,%E4%B9%9F%E5%B0%B1%E6%98%AF%E5%BD%93%E5%89%8D%E9%98%9F%E5%88%97%E5%8F%AA%E5%89%A9%E4%B8%8B%E4%B8%80%E4%B8%AA%E5%85%83%E7%B4%A0%0D%0A%09%09%09rear = front;%0D%0A%09%09%7D%0D%0A
 %09%09E valu
@@ -1891,17 +1891,16 @@
 e;%0D%0A%09%7D%0D%0A
-%09
 %0D%0A%09@Over

Repair the bug: if remove all the elements from the linked queue, there is no way to add element into it.