【问题标题】:Can an object like node update itself without any need of giving it an updated value?像节点这样的对象可以在不需要给它更新值的情况下更新自己吗?
【发布时间】:2019-07-11 15:06:39
【问题描述】:

(在 insert 方法中):在 else 语句中,我不明白“front.next”是如何使用以下行更新的:“prev.next = newNode”。理论上,我理解它,但实际上,虽然“prev”从“curr”中获取它的价值,它从“front”本身获得它的价值,但没有办法因为“prev”而更新front。他们是如何互相交谈的?

(插入方法)我尝试过调试,当它到达执行 => prev.next = newNode 的 else 语句时; front.next 也得到更新,我只是不明白,因为 front 无处被再次初始化。前面是它自己的一个对象。

public class SinglyLinkedList<T>
{
// inner class being created:
protected class Node<T extends Comparable<T>>
{
    T val;
    Node<T> next;

    Node(T val)
    {
        this.val = val;
        this.next = null;
    }

    Node(T val, Node n)
    {
        this.val = val;
        this.next = n;
    }
}

private Node front, tail;

public SinglyLinkedList()
{
    this.front = this.tail = null;
}

// print method:
public void print()
{
    // print the contents of the list
    Node curr = front;
    while (curr != null)
    {
        System.out.println(curr.val + " ");
        curr = curr.next;
    }
}
// insert method:
public void insert(T val)
{
    Node newNode = new Node((Comparable) val);
    // make a new node
    if (front == null)
    {
        // empty list
        front = tail = newNode;
    }
    else
    {
        // list is not empty
        Node curr = front, prev = null;
        // look for insert point.
        while (curr != null && curr.val.compareTo(val) < 0)
        {
            prev = curr;
            curr = curr.next;
        }
        // insert node before curr
        newNode.next = curr;
        if (curr == front)
        {
            // update front
            front = newNode;
        }
        else
        {
            // update node before
            prev.next = newNode;
        }
        if (tail.next != null)
        {
            // move tail to last node
            tail = tail.next;
        }
    }
}

}

我希望 curr 继续使用 curr.next 填充节点链,并使用“prev”作为在两个节点之间添加节点的过程中使用的临时节点。

我也没想到 print 方法会起作用,因为它从前端节点开始。从理论上讲,从前端节点开始确实有意义,但是查看我的代码如何“前端”不等于任何值,而是“curr”等于“前端”,让我觉得“前端”不应该有访问其余节点链。

我希望“front.next”为空,但事实并非如此。

【问题讨论】:

    标签: java eclipse linked-list nodes singly-linked-list


    【解决方案1】:

    好吧,根据你的代码,front 是链表的第一个节点,它实际上等于某个值(一个真正的节点),因为你的代码将它设置为这样一个

    if (front == null)
    {
        // empty list
        front = tail = newNode;
    }
    

    if (curr == front)
    {
        // update front
        front = newNode;
    }
    

    看!您确实将其指向具有给定值的某个节点。

    关于更新问题。我认为您可能总是在前端节点旁边插入一个新节点。在这种情况下,prev 指向与front 相同的节点。所以如果你更新prev,你也更新front

    【讨论】:

    • 有一种情况,虽然它没有进入 if 语句并跳到 else 语句。在某些情况下,它永远不会进入 else 语句!我真的很感谢你回来做这件事。
    猜你喜欢
    • 2021-08-06
    • 1970-01-01
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-06
    • 2021-09-26
    相关资源
    最近更新 更多