有关CTCI的Java Queue实现的问题

时间:2015-09-28 20:01:16

标签: java queue

我正在研究Cracking the Code Interview 5th Edition中的Queue实现。

入队的解释如下:

class Queue {
    Node first, last;

    void enqueue(Object item) {
        // This indicates the Queue is empty
        // so we set both first and last as 
        // the same item
        if(first == null) {
            last = new Node(item);
            first = last;
        } else {
            last.next = new Node(item);
            last = last.next;
        }
    }
}

我理解if语句中发生了什么。此条件处理空队列。因此,如果队列为空,并且我们尝试将项目添加到队列中,则添加的项目既是第一项也是最后一项。

然而,我不理解的是在else语句中发生了什么。该书首先将该项目指定为last.next,然后将last指定为last.next。难道这不会使最后一个和最后一个的下一个元素相同吗?另外,我说明了队列。这是lastlast.next的位置的准确说明吗?

[      |      |      |      ]

    ^     ^
  last  last.next

1 个答案:

答案 0 :(得分:3)

else部分中的代码:

1: last.next = new Node(item);
2: last = last.next;

这是我们开始的LL:

(a) -> (b) -> (c)
 ^first        ^last

我们称为入队(d)

第1行之后:

(a) -> (b) -> (c) -> (d)
 ^first        ^last

因此,我们看到第1行在列表末尾创建了一个新元素,但last仍然指向(c)

第2行之后:

(a) -> (b) -> (c) -> (d)
 ^first               ^last

现在,last指向(d),它恰当地没有next个节点。

您看,(c)永远不会消失,只是移动last 引用

至于为什么这就是它的工作原理,这一切都归结为对象是Java中的引用。

考虑以下代码:

Object x = 300;
Object y = 500;
Object z = x;

//here, x = 300, y = 500, z = 300

x = y;
//now, x = 500, y = 500, z = 300
//because the actual object that x initially pointed to was not changed, only x as a reference was changed.

如果列表的大小分别为n=0n=1

NULL
^first,last

NULL    (a)
^first   ^last

(a)
 ^first,last

然后另一个电话

(a)
 ^first,last
(a)     ->     (b)
 ^first,last

(a)     ->     (b)
 ^first         ^last

希望有所帮助

相关问题