java如何new链表
在Java中创建链表
在Java中,链表可以通过两种主要方式实现:使用LinkedList类或自定义链表节点类。以下是两种方法的详细说明。
使用LinkedList类
LinkedList是Java集合框架的一部分,直接使用该类可以快速创建链表。
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
list.add("A");
list.add("B");
list.add("C");
System.out.println(list); // 输出: [A, B, C]
}
}
自定义链表节点类
如果需要更灵活的控制,可以自定义链表节点类。
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
public class Main {
public static void main(String[] args) {
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
Node current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
// 输出: 1 2 3
}
}
添加元素到链表
无论是使用LinkedList还是自定义链表,添加元素的方法类似。
// 使用LinkedList
LinkedList<String> list = new LinkedList<>();
list.add("D");
// 自定义链表
Node newNode = new Node(4);
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
遍历链表
遍历链表是常见的操作,可以通过循环实现。
// 使用LinkedList
for (String item : list) {
System.out.println(item);
}
// 自定义链表
Node current = head;
while (current != null) {
System.out.println(current.data);
current = current.next;
}
删除链表元素
删除元素时需要注意链表的连接。
// 使用LinkedList
list.remove("B");
// 自定义链表
if (head.data == 1) {
head = head.next;
}
链表与数组的转换
链表可以方便地与数组相互转换。

// LinkedList转数组
String[] array = list.toArray(new String[0]);
// 数组转LinkedList
LinkedList<String> newList = new LinkedList<>(Arrays.asList(array));
通过以上方法,可以灵活地在Java中创建和操作链表。






