如何在不使用 head 的情况下打印链表的元素



我正在尝试在不使用头节点的情况下重写此程序,有什么帮助吗?

我已经尝试了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;
}
}
}

您可以在第一次迭代中初始化您的头部。下面是一个简单的代码:

class Node {
int value;
Node next;
public Node(int v) {   //gives the node a value
value = v;
}
}

class HelloWorld {
public static void main (String[] args) throws Exception {
int[] array = {1, 2, 5, 3, 0, 8};
Node head = null, current = null;
for (int i = 0; i < array.length; i++) {
if(head == null){
head = new Node(array[i]);
current = head;
}
else{
current.next = new Node(array[i]);
current = current.next;
}
}
current = head; 
while (current != null) {  
System.out.println(current.value);
current = current.next;
}
}
}

我强烈建议您学习一些有关算法和数据结构的课程,以加强您的基础知识。这是一个好的开始:Codemonk

最新更新