Java 混乱的队列实现
我很难理解队列的这种实现,更具体地说,是排队和退队方法。 不管我怎么接近它,我都无法控制它Java 混乱的队列实现,java,Java,我很难理解队列的这种实现,更具体地说,是排队和退队方法。 不管我怎么接近它,我都无法控制它 class Node { int val; Node next; Node(int x) { val = x; next = null; } } class Queue{ Node first, last; public void enqueue(Node n){ if(first == null){
class Node {
int val;
Node next;
Node(int x) {
val = x;
next = null;
}
}
class Queue{
Node first, last;
public void enqueue(Node n){
if(first == null){
first = n;
last = first;
}else{
last.next = n;
last = n;
}
}
public Node dequeue(){
if(first == null){
return null;
}else{
Node temp = new Node(first.val);
first = first.next;
return temp;
}
}
}
排队方法如何工作?
在这里,我们只是“忘记”最后一个对象,并将其设置为对象n:
last.next = n;
last = n;
如果我们只接触了节点一次,那么这个出列是如何工作的呢。第一个如何拥有一系列的first.next
值
Node temp = new Node(first.val);
first = first.next;
return temp;
下面是这些方法如何工作的逐步示例 排队 n
一(第一)->二->三->四(最后)//方法调用前的列表
last.next = n; // Add n to the end of the queue
Node temp = new Node(first.val);
一(第一)->二->三->四(最后)->n一(第一)->二->三->四->n(最后)//方法调用后的列表
last.next = n; // Add n to the end of the queue
Node temp = new Node(first.val);
出列 一(第一)->二->三->四(最后)//方法调用前的列表
last.next = n; // Add n to the end of the queue
Node temp = new Node(first.val);
一(第一,临时)->二->三->四(最后)一(临时)->两(第一)->三->四(最后)//方法调用后的列表
last.next = n; // Add n to the end of the queue
Node temp = new Node(first.val);
请注意,
one
仍然指向two
,但是指向first
的指针已更新,因此不再有对one
的访问。队列由单个链接列表实现。第一个和最后一个只是两个“指针”,指向列表中的第一个和最后一个节点
当调用enqueue时,它将向列表中添加(追加)节点,当调用dequeue时,将弹出第一个节点。因此,队列看起来像:
n->n->n->n->...n
linked list direction: ->
en/dequeue direction : <-
排队后(E):
dequeue()之后:
已返回节点F
(first==null)检查仅用于检查队列是否为空
关于此零件代码,请检查以下行中的注释:
Node temp = new Node(first.val); //create a new node tmp, same value with first, but without "next"
first = first.next; //make the 2nd (first.next) as new first
return temp; // return the new created node (tmp)
不清楚你在问什么。代码看起来非常正常。你似乎不了解链表的基本工作原理(这是语言不可知论),就像@Ordous所说的,你误解了对象引用。这说明了链表是如何工作的(与此队列实现非常类似)。