gpt4 book ai didi

java - 了解链表队列的入队方法

转载 作者:行者123 更新时间:2023-12-01 13:49:46 25 4
gpt4 key购买 nike

我无法理解链表队列的入队方法的代码。我理解 dequeue()、isEmpty()、First() 和 size()。首先,这是 LinearNode 类来创建新的节点对象:

public class LinearNode<T> {
private T element;
private LinearNode<T> next;

/**
* Constructor: Creates an empty node.
*/
public LinearNode() {
next = null;
element = null;
}

/**
* Constructor: Creates a node storing the specified element.
* @param elem The specified element that is to be kept by this LinearNode.
*/
public LinearNode(T elem) {
next = null;
element = elem;
}

/**
* Returns the node that follows this one.
* @return The node that follows this one.
*/
public LinearNode<T> getNext() {
return next;
}

/**
* Sets the node that follows this one.
* @param node The node which is to follow this one.
*/
public void setNext(LinearNode<T> node) {
next = node;
}

/**
* Returns the element stored in this node.
* @return The element that is kept within this node.
*/
public T getElement() {
return element;
}

/**
* Sets the element stored in this node.
* @param elem The element that is to be kept within this node.
*/
public void setElement(T elem) {
element = elem;
}
}

这是入队方法

public void enqueue(T element) {
LinearNode<T> tmp = new LinearNode<T>(element);
if (isEmpty()) {
// set-up front to point to the new node
front = tmp;
} else {
// add the node after the old tail node
rear.setNext(tmp);
}
// update rear to point to the new node
rear = tmp;
count++; // increment size
}

我感到困惑的代码部分是 rear.setNext(tmp);我的意思是不应该是 temp.setNext(rear);如何使用 .setNext(); 方法关于LinearNode<T> rear;当你没有创建名为“rear”的新对象时,我能看到的唯一新对象称为“temp” ??

编辑这里是包含 Enqueue 方法的 LinkQueue 类:

public class LinkedQueue<T> implements QueueADT<T> {
private LinearNode<T> front; // front node of the queue
private LinearNode<T> rear; // rear node of the queue
private int count; // the current size of the queue

/**
* Constructor: Creates an empty Queue.
*/
public LinkedQueue() {
count = 0;
/* the following assignments are not actually necessary as references
* are initialised automatically to null,
* but they are included for clarity.
*/
front = null;
rear = null;
}

最佳答案

从代码中我可以理解,front和rear只是指针。它们用于指向队列的第一个和最后一个节点。所以当你说:

rear.setNext(tmp);

您正在队列的最后一个节点之后标记新节点。

考虑这个队列:1,2,3,4

在此队列中,前面=1后=4

enqueue(5)

这导致 tmp=5

rear.setNext(5) 结果

1,2,3,4,5

rear=tmp 结果after=5 将后指针重置为最后一个节点

关于java - 了解链表队列的入队方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20054783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com