Java 链表实现中的入队操作是如何赋值的
How do assignments work in enqueue operation in Java linked list implementation
我最近尝试在 Java 中使用 linked 列表实现一个队列。 enqueue
,向队列添加项的函数如下
void enqueue(int key)
{
// Create a new LL node
Node temp = new Node();
// If queue is empty, then new node is front and rear both
if (this.rear == null) {
temp.setData(key);
this.front = this.rear = temp;
return;
}
temp.setData(key);
// Add the new node at the end of queue and change rear
this.rear.setLink(temp);
this.rear = temp;
}
class Node{
private int data;
private Node link;
public int getData(){
return this.data;
}
public void setData(int data){
this.data = data;
}
public Node getLink(){
return this.link;
}
public void setLink(Node link){
this.link = link;
}
public Node(){
}
}
这是按预期工作的,但我无法理解的是这个 function.first 的最后两行我们将当前后方的 link 设置为新节点,然后立即 rear
被分配了新节点。 rear
中存储的先前值发生了什么变化?
rear 只是指向插入队列中的最后一个元素的引用。假设您当前的队列具有以下元素 1 -> 2 -> 3(rear)。 rear 现在指向 3。现在假设您调用 enqueue(4)。当前rear的link(next)指针应该指向新节点。 this.rear.setLink(temp)
行正是这样做的。当前队列的内容将是 1 -> 2 -> 3(rear) -> 4。我们需要更新新的 rear。 this.rear = temp
正是这样做的。最终队列的内容将是 1 -> 2 -> 3 -> 4(rear)
我最近尝试在 Java 中使用 linked 列表实现一个队列。 enqueue
,向队列添加项的函数如下
void enqueue(int key)
{
// Create a new LL node
Node temp = new Node();
// If queue is empty, then new node is front and rear both
if (this.rear == null) {
temp.setData(key);
this.front = this.rear = temp;
return;
}
temp.setData(key);
// Add the new node at the end of queue and change rear
this.rear.setLink(temp);
this.rear = temp;
}
class Node{
private int data;
private Node link;
public int getData(){
return this.data;
}
public void setData(int data){
this.data = data;
}
public Node getLink(){
return this.link;
}
public void setLink(Node link){
this.link = link;
}
public Node(){
}
}
这是按预期工作的,但我无法理解的是这个 function.first 的最后两行我们将当前后方的 link 设置为新节点,然后立即 rear
被分配了新节点。 rear
中存储的先前值发生了什么变化?
rear 只是指向插入队列中的最后一个元素的引用。假设您当前的队列具有以下元素 1 -> 2 -> 3(rear)。 rear 现在指向 3。现在假设您调用 enqueue(4)。当前rear的link(next)指针应该指向新节点。 this.rear.setLink(temp)
行正是这样做的。当前队列的内容将是 1 -> 2 -> 3(rear) -> 4。我们需要更新新的 rear。 this.rear = temp
正是这样做的。最终队列的内容将是 1 -> 2 -> 3 -> 4(rear)