java - 关于 CTCI 的 Java 队列实现的问题

标签 java queue

我正在研究《破解代码面试第五版》中的队列实现。

enqueue的解释如下:

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

最佳答案

else部分的代码:

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

这是我们开始的 LL:

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

我们调用enqueue(d)

第 1 行运行后:

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

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

第 2 行运行后:

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

现在,last 指向 (d),它相应地没有 next 节点。

你看,(c) 永远不会消失,它只是最后引用移动 .

至于为什么它是这样工作的,这一切都归结于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

希望有帮助

关于java - 关于 CTCI 的 Java 队列实现的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32830836/

相关文章:

java - 如何 Javadoc 类的单个枚举

java - 分配时间与系统时间相同时的运行方法

java - SpringMVC : Multi viewresolver

C:带有链表实现的奇怪的段错误

c - 使用 BFS 改进 8-Puzzle

java - 使用 java.util.regex API 的正则表达式 - java

java - Spring AOP : "no declaration can be found for element ' aop:config' "

SWIFT - OperationQueue.main.addOperation 和 DispatchQueue.main.async 之间有什么区别?

c++ - for循环的每次迭代都添加一个新语句。二维数组排队

algorithm - Com 端口队列延迟计量