【问题标题】:Can someone explain a few lines about Linked List in Java?有人可以解释几行关于 Java 中的链表吗?
【发布时间】:2016-04-07 08:32:55
【问题描述】:

我目前正在为考试而学习,我不太了解链表。我想知道是否有人可以向我解释几行代码。

class Node{
  Node next, previous;
    final int value;
  Node(int v){
    value = v;
  }
}

public class Linked{
  Node start = null, end = null;
  // Add a node on the end
  void append(int v){
    Node n = new Node(v);
    if (start == null){
      start = end = n;
      return;
    }
    end.next = n;
    n.previous = end;
    end = n;
  }
// Add a node to the front
void prepend(int v){
  Node n = new Node(v);
  if (start == null){
    end = start = n;
    return;
  }
  n.next = start;
  start.previous = n;
  start = n;
 }
}

我需要解释的行是 append 和 prepend 方法中的最后 3 行。 cmets 解释了每种方法的目的,但我不明白在这些代码行中实际做了什么。提前致谢。

【问题讨论】:

  • 将列表保存在一起的链接被更改以反映当前状态。

标签: java linked-list


【解决方案1】:

追加

当你想在列表末尾添加一个节点时,它应该链接到当前的最后一个节点:

end.next = n; // the current last node points to the new node
n.previous = end; // the new node points back to the previous node 
                  // (which is the current last node)
end = n; // the new node becomes the last node

prepend 类似:

n.next = start; // the node that follows the new node is the current first node
start.previous = n; // the previous node of the current first node is the new node
start = n; // the new node becomes the first node

【讨论】:

    【解决方案2】:

    Node 类显示列表中有称为节点的项目。这些项目跟踪当前节点之前和之后的项目(下一个和上一个)。 Linked 类为列表的开头和结尾创建一个 Node 对象,并具有两个方法:append 将在当前节点之后添加一个整数 v,prepend 将在当前节点之前的节点添加一个整数。

    【讨论】:

      【解决方案3】:

      您将在列表的尾部end 之后创建一个新节点。

      end.next = n;
      

      同样,由于它是双向链接的,n 现在将有一个先前的节点 end

      n.previous = end;
      

      最后,由于新节点现在是列表的尾部,我们将其分配给end

      end = n;
      

      Prepend 遵循类似的逻辑。前一个头 start 将出现在新节点之后。

      n.next = start;
      

      由于是双向链接的,start需要知道之前的节点是新的节点。

      start.previous = n;
      

      最后,我们的新节点就是新的头。

      start = n;
      

      【讨论】:

        【解决方案4】:

        想象一下,如果你有一条链,链的每个部分(节点)只知道它前面的那个和它后面的那个。 所以,现在我想将新的部分(节点)附加到链的末尾,我们称之为 N
        A --> B --> C ===> A --> B --> C --> N.
        为了正确插入 N 我需要 N 知道 C 在它后面并且 C 知道 N 在它的前面。所以,现在我将更新 c.next 或在你的情况下将 end.next 更新为 Nn.previous 结束。现在我的新结局是 N 而不是 C

        一开始也是一样。

        A --> B ==> N --> A --> B 我们将更新 AN 并开始。

        【讨论】:

          猜你喜欢
          • 2015-04-20
          • 2020-08-16
          • 2020-11-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-05-29
          • 2010-12-13
          • 1970-01-01
          相关资源
          最近更新 更多