编写Java代码实现单链表 ?
参考答案:
下面是一个简单的Java实现单链表的代码:
public class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
public class LinkedList {
Node head;
public LinkedList() {
head = null;
}
// 在链表末尾添加节点
public void append(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
return;
}
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
// 打印链表
public void printList() {
Node current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.append(1);
list.append(2);
list.append(3);
list.append(4);
list.printList(); // 输出: 1 2 3 4
}
}
这个代码定义了两个类:Node
和 LinkedList
。Node
类表示链表中的一个节点,包含一个数据字段 data
和一个指向下一个节点的指针 next
。LinkedList
类表示整个链表,包含一个指向链表头部的指针 head
。
LinkedList
类有两个主要的方法:append
和 printList
。append
方法用于在链表末尾添加一个新的节点,printList
方法用于打印链表中的所有节点。
在 main
方法中,我们创建了一个 LinkedList
对象,并添加了四个节点,然后调用 printList
方法打印链表中的所有节点。