题目
用环形链表实现Queue。环形链表也是一条链表,只是没有任何结点链接为空,且只要链表非空则last.next的值就为first。只能使用一个Node类型的实例变量(last)。
思路
用last.next代替first即可。
代码
package Chap1.$3;
import edu.princeton.cs.algs4.StdIn;
public class E29
{
private class Node
{
Node next;
int item;
}
private Node last;
private int N = 0;
public void en(int item) ////⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️
{
Node oldlast = last;
last=new Node();
last.item = item;
if (isEmpty()) last.next = last;
else
{
last.next = oldlast.next;
oldlast.next = last;
}
N++;
}
public int de()
{
int item = last.next.item;
N--;
if(isEmpty()) last =null;
else
{
last.next = last.next.next;
}
return item;
} ////⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️
public boolean isEmpty()
{
return N == 0;
}
public int size()
{
return size();
}
public static void main(String... args)
{
E29 e = new E29();
while (!StdIn.isEmpty())
{
e.en(StdIn.readInt());
}
while (!e.isEmpty())
{
System.out.print(e.de());
}
}
}