描述:使用链表(LinkedList) 实现一个对列。给出最后一个Node ;
思路:
1.环形链表的实现方式:最后一个节点的next指向第一个节点。
2.入列方式:将最后一个节点last指向新的节点,
并将新的节点node的next指向last.next(原节点last的next, 这里为首节点).
最后把新节点node定义为最后一个节点last.
3.出列方式:找到最后一个节点的next,也就是首节点,first = last.next
然后将last.next 指向 first.next;跳过首节点first,定义首节点first.next为新的首节点。
输出 first.item
注意:不能直接输出 last.next.item;因为只有一个节点的这种情况会导致last 为空,输出的item也必然为空的情况!
思路草图:
代码如下:
package chapter1.a3;
/**
* Created by fengjw on 2017/8/13
* Code Change The World!
*/
public class Example1329<Item> {//circle queue
private Node
last;
private class Node{
Item item;
Node next;
public Node(Item item){
this.item = item;
}
}
/**
* enqueue operation
*/
public void enqueue(Item item){
Node node = new Node(item);
if (last ==null){
last = node;
last.next =last;
}else {//cycle
Node origin = last.next;
last.next = node;
node.next = origin;// origin is the first Node
last = node;// by the 'last' point to the last Node
}
}
/**
* dequeue operation
*/
public Itemdequeue(){
if (last ==null){
throw new NullPointerException("queue is empty!");
}
Node first = last.next;
if (first ==
last){
last = null;// '@Important'
}else {
last.next = first.next;
}
return first.item;// or last.next.item? Error!
// Because : if LinkedList only have one Node,
//'last = null'; return last.next is mean return null; not get the item.
}
}