简体   繁体   English

Java链表实现中的入队操作中分配如何工作

[英]How do assignments work in enqueue operation in Java linked list implementation

I recently tried to implement a queue with linked list in Java. 我最近尝试用Java实现带有链接列表的队列。 enqueue , The function to add items to the queue is as follows. 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(){
    }
}

This is working as expected, but the thing that I cannot understand is the last two lines of this function.first we set the link of current rear to the new node, then immediately rear is assigned the new node. 这按预期工作,但我不明白的是此函数的最后两行。首先我们将当前后方的链接设置为新节点,然后立即为rear分配新节点。 What happened to the previous value stored in rear ? rear存储的先前值发生了什么?

rear is just a reference which points to the last element inserted into the Queue. 后方只是指向插入队列中最后一个元素的参考。 Lets say your current queue has the following elements 1 -> 2 -> 3(rear) . 可以说您当前的队列具有以下元素1-> 2-> 3(rear) The rear is now pointing to 3. Now let's say you call enqueue(4). 现在, 后方指向3。现在,假设您调用enqueue(4)。 The current rear's link(next) pointer should point to the new node. 当前后方的 link(next)指针应指向新节点。 The line this.rear.setLink(temp) is doing exactly that. 这行this.rear.setLink(temp)正是这样做的。 The current queue's contents will be 1 -> 2 -> 3(rear) -> 4 . 当前队列的内容将为1-> 2-> 3(后方)-> 4 We need to update the new rear . 我们需要更新新的后部 this.rear = temp is doing exactly that. this.rear = temp就是这样做的。 Eventually the queue's contents will be 1 -> 2 -> 3 -> 4(rear) 最终,队列的内容将为1-> 2-> 3-> 4(后方)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM