数据结构单链表Java
时间: 2024-05-08 10:13:20 浏览: 11
单链表是一种常见的数据结构,用于存一系列具有相同类型的元素。在Java中,可以使用类来实现单链表。
在单链表中,每个元素被称为节点(Node),每个节点包含两部分:数据域(存储元素的值)和指针域(指向下一个节点的指针)。最后一个节点的指针域为空。
以下是一个简单的单链表的Java实现示例:
```java
// 定义节点类
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
// 定义单链表类
class LinkedList {
Node head;
public LinkedList() {
this.head = null;
}
// 在链表末尾添加节点
public void add(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
} else {
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 class Main {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.add(1);
list.add(2);
list.add(3);
list.printList(); // 输出:1 2 3
}
}
```
以上代码演示了如何创建一个单链表,并在链表末尾添加节点。然后,通过遍历链表打印出节点的值。