我们如何可以创建不同的参考n个节点?

问题描述 投票:1回答:3

我要创建链表的数据管理的项目(单)我很困惑我们如何可以创建不同的参考节点。据我所知节点是一个对象,并创建一个对象,我们简单地写(classname ref = new constructor())。现在我想要做的是,我要救第一个雇员数据

在一个节点,所述第二节点上的第二雇员数据....和第n个节点上的第n个雇员数据。这里是我的问题,对于第二点,我需要重新编写语法创建第二个节点,如果我想保存员工的n条记录我怎么能写n个节点的语法的。我知道,一个节点包含两个东西是数据和第二点的地址。例如:

class node {
    String data ; 
    node next;
    node(String data , node a ){
        this.data = data;
        next = a ;
    }
}
main(){         
    node n1 = new node("a",n2); 
    node n2 = new node("b",null);
    till nth.
        /*well i thought that if i could loop this so that it automatically 
         *create nodes but even if i did that then the data will be saved on same 
         reference/address */
}

希望我就像你需要澄清我的问题。

java
3个回答
3
投票

简单地重复并保持到您在最后一次迭代中创建的节点的引用。

List<String> data = Arrays.asList("a", "b", "c");

Node previousNode = null;
for (String datum : data)
{
    previousNode = new Node(datum, previousNode);
}
//previousNode now contains a reference to the last node (C)

0
投票

有没有办法在一个循环中创建多个不同名称的变量。然而,你可以把它们放在一个列表,或者 - 因为你基本上是建立一个链表 - 你可能只是想保留最近创建的节点,当你需要对他们进行任何动作遍历嵌套的节点。

这会给你在变量n的最后一个节点:

Node n;
Arrays.asList("a", "b", "c", ...).forEach(s -> n = new Node(s, n));

这会给你的节点列表:

Node n;
List<Node> nodes = new ArrayList<>();
for (String s : Arrays.asList("a", "b", "c", ...)) {
  n = new Node(s, n);
  nodes.add(n);
}

0
投票

Algorithm

  1. 创建headref,将保留您列表的开始
  2. 遍历列表。对于每次迭代创建指定为head.next = newNode
  3. 推进head => head = head.next
  4. 重复2根据需要3
  5. 你的名单将在ref作为其头

Code

List<String> list = Arrays.asList("a", "b", "c", "d", "e");
Node head = new Node(list.get(0), null);
Node ref = head;

for (int i = 1; i < list.size(); i++) {
  head.next = new Node(list.get(i), null);
  head = head.next;
}

// Your list is ready, you can iterate through it as such
while (ref != null) {
  System.out.println(ref.data);
  ref = ref.next;
}
© www.soinside.com 2019 - 2024. All rights reserved.