// 示例代码:Java中的链表数据结构实现
// 定义链表节点类
class ListNode {
int val; // 节点存储的值
ListNode next; // 指向下一个节点的指针
// 构造函数
ListNode(int val) {
this.val = val;
this.next = null;
}
}
// 定义链表类
class LinkedList {
private ListNode head; // 链表的头节点
// 构造函数
public LinkedList() {
this.head = null;
}
// 在链表尾部添加一个节点
public void add(int val) {
ListNode newNode = new ListNode(val);
if (head == null) {
head = newNode;
} else {
ListNode current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
}
// 打印链表中的所有节点值
public void printList() {
ListNode current = head;
while (current != null) {
System.out.print(current.val + " ");
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
}
}
val 和一个指向下一个节点的引用 next。head。提供了添加节点和打印链表的方法。这个示例展示了如何在 Java 中实现一个简单的单向链表,并对其进行基本操作。
上一篇:java file转base64
下一篇:java去空格
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站