专业的JAVA编程教程与资源

网站首页 > java教程 正文

Java算法面试-将一个数组转换成链表?

temp10 2024-10-11 18:26:33 java教程 15 ℃ 0 评论

在Java中,可以通过创建一个链表节点类,然后遍历数组并逐个创建链表节点来将数组转换成链表操作。如下所示。

第一步、定义链表节点

这里我们先来简单的定义一个单链表结构,如下所示。

Java算法面试-将一个数组转换成链表?

// 定义链表节点类
class ListNode {
    int val;
    ListNode next;

    ListNode(int val) {
        this.val = val;
        this.next = null;
    }
}

第二步、实现链表转换

// 将数组转换成链表的方法
public static ListNode arrayToLinkedList(int[] array) {
    if (array == null || array.length == 0) {
        return null; // 如果数组为空,返回null
    }

    // 创建链表头节点
    ListNode head = new ListNode(array[0]);
    ListNode current = head;

    // 遍历数组,创建链表节点并链接
    for (int i = 1; i < array.length; i++) {
        current.next = new ListNode(array[i]);
        current = current.next;
    }

    return head; // 返回链表头节点
}

首先先来检查数组的长度是否为0,如果为0则直接返回null,否则继续执行后续操作。创建链表的头节点,并初始化为数组的第一个元素。接下来就是遍历数组创建节点将其连接到后续的节点上,最终返回头结点对象。

第三步、输出结果

实现一个方法通过头结点来遍历链表打印出每个链表对象,如下所示。

// 打印链表的方法,便于测试
public static void printLinkedList(ListNode head) {
    ListNode current = head;
    while (current != null) {
        System.out.print(current.val + " -> ");
        current = current.next;
    }
    System.out.println("null");
}

完整代码实现

// 定义链表节点类
class ListNode {
    int val;
    ListNode next;

    ListNode(int val) {
        this.val = val;
        this.next = null;
    }
}

public class ArrayToLinkedList {
    // 将数组转换成链表的方法
    public static ListNode arrayToLinkedList(int[] array) {
        if (array == null || array.length == 0) {
            return null; // 如果数组为空,返回null
        }

        // 创建链表头节点
        ListNode head = new ListNode(array[0]);
        ListNode current = head;

        // 遍历数组,创建链表节点并链接
        for (int i = 1; i < array.length; i++) {
            current.next = new ListNode(array[i]);
            current = current.next;
        }

        return head; // 返回链表头节点
    }

    // 打印链表的方法,便于测试
    public static void printLinkedList(ListNode head) {
        ListNode current = head;
        while (current != null) {
            System.out.print(current.val + " -> ");
            current = current.next;
        }
        System.out.println("null");
    }

    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5};
        ListNode head = arrayToLinkedList(array);
        printLinkedList(head);
    }
}

上面的代码展示了如何将一个数组转换成一个单向链表操作,我们可以根据这个代码对相关实现进行扩展,例如我们可以添加其他类型数据的处理,或者是可以实现双向链表等操作。

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表