-3
public CarList(CarList cl)
{
    if(cl == null) throw new NullPointerException();
    if (cl.head == null)
        head = null;
    else
    {
        // Notice that you cannot issue head = cl.head; otherwise both heads will point at the passed list;

        head = null;
        // Now create and copy all the nodes in the list
        CarNode temp, temp2, temp3;
        temp = cl.head;
        temp2 = null;
        temp3 = null;


        while(temp != null)
        {
            if (temp2 == null)      // The case for the first node
            {
                temp2 = new CarNode(temp.getCar(), null);
                head = temp2;
            }
            else
            {
                temp3 = new CarNode(temp.getCar(), null);
                temp2.setNext(temp3);
                temp2 = temp3;
            }

            temp = temp.getNext();
        }
        // Avoid privacy leak; set all temporary pointers to null 
        temp = temp2 = temp3 = null;
    }
}

我不太明白循环的作用......我无法解析代码。隐私权是否是由于临时变量持有地址这一事实?

4

1 回答 1

1

它用于:

    head = temp2;

您的标签准确地说明了这里发生了什么。CarList 是一个表示单链表的类,其中列表的每个元素都包装在一个 CarNode 中,该 CarNode 包含该元素以及指向列表中下一个元素的链接。

'head' 变量指向列表中的第一个 CarNode。有问题的 while 循环,虽然它的变量名有问题,但它只是将参数列表复制到正在实例化的那个,为每个元素创建一个新的 CarNode。浏览它以获取 4 元素示例,您会看到它在做什么。

您最好查看“Lisp CAR 函数”以获取更多信息。 这个页面也有很多关于它的信息。

于 2013-04-12T02:03:41.350 回答