我要创建链表的数据管理的项目(单)我很困惑我们如何可以创建不同的参考节点。据我所知节点是一个对象,并创建一个对象,我们简单地写(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 */
}
希望我就像你需要澄清我的问题。
简单地重复并保持到您在最后一次迭代中创建的节点的引用。
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)
有没有办法在一个循环中创建多个不同名称的变量。然而,你可以把它们放在一个列表,或者 - 因为你基本上是建立一个链表 - 你可能只是想保留最近创建的节点,当你需要对他们进行任何动作遍历嵌套的节点。
这会给你在变量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);
}
head
和ref
,将保留您列表的开始head.next = newNode
head
=> head = head.next
ref
作为其头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;
}