【发布时间】:2013-12-02 00:23:21
【问题描述】:
我无法理解链表队列的入队方法的代码。我理解 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;
}
【问题讨论】:
-
谁和在哪里是前面和后面?
-
刚刚编辑的帖子看看
标签: java linked-list queue