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

标签 java list nodes

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

我已经尝试过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/

相关文章:

java - 如何修复 Spring Boot 应用程序中 SimpleJdbcInsert 中的错误

java - 使用 pop3 按日期降序获取邮件

javascript - 如何保留文本节点中的空白?

java - AWT 字符串宽度取决于 DPI

java - 如何使用 Hibernate OGM 和 MongoDB 删除数据库或集合

python - python中if语句中的生成器

python - 从jira附件python中获取附件ID

python - 查找两个列表的重叠,保留序列顺序

node.js - 使用功能通过 Node 获取获取数据

javascript - 如何从一个点(X 和 Y 坐标)创建一个范围对象?