码迷,mamicode.com
首页 > 其他好文 > 详细

1.3.41

时间:2018-05-24 18:07:20      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:nod   题目   tail   his   private   出队   一个   other   span   

question:

Copy a queue. Create a new constructor so that

Queue<Item> r = new Queue<Item>(q);

makes r a reference to a new and independent copy of the queue q. You should be able to push and pop from either q or r without influencing the other. Hint: Delete all of the elements from q and add these elements to both q and r.

answer:

//要注意queue的特性只能尾enqueue,头dequeue,且一次只能对一个元素进行操作

//不过题目中给的提示已经很明显了

import edu.princeton.cs.algs4.*;

public class CopyQueue<Item>
{
    private class Node 
    {
        Item item;
        Node next;
    }
    
    private Node head;
    private Node tail;
    private int N;
    
    public CopyQueue()
    {
        head = null;
        tail = null;
        N = 0;
    }
    
    public CopyQueue(CopyQueue<Item> queue)//注意CopyQueue<Item>
    {
        head = null;
        int size = queue.size();
        while(size > 0)//此题关键所在
        {
            
            Item item = queue.dequeue();
            this.enqueue(item);
            queue.enqueue(item);
            size--;
        }
    }
    
    
    public int size()
    {
        return N;
    }
    
    public void enqueue(Item item)//入队
    {
        Node node = new Node();
        node.item = item;
        node.next = null;
        if(head == null)
        {
            N++;
            tail = head = node;
            return;
        }
        N++;
        tail.next = node;
        tail = node;
    }
    
    public Item dequeue()//出队
    {
        if(N == 0)
        {
            return null;
        }
        Item item = head.item;
        head = head.next;
        N--;
        return item;
    }
    
    public static void main(String[] args)
    {
        CopyQueue<String> q1 = new CopyQueue<String>();
        q1.enqueue("w");
        q1.enqueue("j");
        q1.enqueue("c");
        CopyQueue<String> q2 = new CopyQueue<String>(q1);
        for(int i = 0; i < 3; i++)
        {
            StdOut.print("q1\t" + q1.dequeue());
            StdOut.print("\tq2\t" + q2.dequeue() + "\n");
        }
    }
}

 

1.3.41

标签:nod   题目   tail   his   private   出队   一个   other   span   

原文地址:https://www.cnblogs.com/w-j-c/p/9083804.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!