我正在尝试在不使用头节点的情况下重写此程序,有什么帮助吗?
我已经尝试过getFirst()
方法将指针设置为链表的第一个元素,但它不起作用。有什么方法可以将链表的第一个值设置为新头,而无需实际创建值为 0
的头?
class Node {
int value;
Node next;
public Node(int v) { //gives the node a value
value = v;
}
}
public class HelloWorld {
public static void main (String[] args) throws Exception {
int[] array = {1, 2, 5, 3, 0, 8};
Node head = new Node(0);
Node current = head;
for (int i = 0; i < array.length; i++) {
// 2. create each node object
Node node = new Node(array[i]);
current.next = node;
current = node;
}
current = head.next;
while (current != null) {
System.out.println(current.value);
current = current.next;
}
}
}
最佳答案
是的,你可以。只需使用数组的第一个元素初始化 Head。
public class HelloWorld {
public static void main (String[] args) throws Exception {
int[] array = {1, 2, 5, 3, 0, 8};
// Initialize head with first element of array.
Node head = new Node(array[0]);
Node current = head;
for (int i = 1; i < array.length; i++) {
// 2. create each node object
Node node = new Node(array[i]);
current.next = node;
current = node;
}
current = head;
while (current != null) {
System.out.println(current.value);
current = current.next;
}
}
}
关于java - 如何在不使用 head 的情况下打印链表的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57368436/