Algs4-1.3.41复制队列采用for方式实现
1.3.41复制队列。编写一个新的构造函数,使用以下代码Queue<Item> r=new Queue<Item>(q);得到的r指向队列q的一个新的独立的副本。可以对q或r进行任意入列或出列操作但它们不会相互影响。提示:从q中取出所有元素再将它们插入q和r。
答:
import java.util.Iterator;
public class Queue<Item> implements Iterable<Item>
{
private int N;
private Node first;
private Node last;
private class Node
{
Item item;
Node next;
}
public Queue()
{
}
public Queue(Queue q)
{
for(Object i:q)
{
//
Node oldlast=last;
last=new Node();
last.item=(Item) i;
last.next=null;
if(isEmpty())
first=last;
else
oldlast.next=last;
N++;
}
}
public boolean isEmpty()
{return N==0;}
public int size()
{return N;}
public void enqueue(Item item)
{
Node oldlast=last;
last=new Node();
last.item=item;
last.next=null;
if(isEmpty())
first=last;
else
oldlast.next=last;
N++;
}
public Item dequeue()
{
Item item=first.item;
first=first.next;
if(isEmpty()) last=null;
N--;
return item;
}
public Iterator<Item> iterator() {return new ListIterator();}
private class ListIterator implements Iterator<Item>
{
private Node current=first;
public boolean hasNext(){return current!=null;}
public void remove(){}
public Item next()
{
Item item=current.item;
current=current.next;
return item;
}//end next
}//end class ListIterator
public static void main(String[] args)
{
Queue<String> q=new Queue<String>();
while(!StdIn.isEmpty())
{
String item=StdIn.readString();
q.enqueue(item);
}//end while
StdOut.println("---Queue q is:");
for(String item:q)
StdOut.println(item+" ");
//
Queue<String> r=new Queue<String>(q);
//
StdOut.println("---After r=new Queue<Item>(q) q is:");
for(String item:q)
StdOut.println(item+" ");
//
q.dequeue();
StdOut.println("---After q.dequeue q is:");
for(String item:q)
StdOut.println(item+" ");
//
StdOut.println("---Queue r is:");
for(String item:r)
StdOut.println(item+" ");
}//end main
}//end class