前天学习了在c++中怎么使用单链表,我在网上学习了在Java中如何实现:
定义节点类:
class Node {
int data; // 存储数据
Node next; // 指向下一个节点的引用
// 构造函数
public Node(int data) {
this.data = data;
this.next = null;
}
}
定义链表类:
class SinglyLinkedList {
Node head; // 链表的头节点
// 在链表头部添加元素
public void addFirst(int data) {
Node newNode = new Node(data);
newNode.next = head;
head = newNode;
}
// 在链表尾部添加元素
public void addLast(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
} else {
Node last = head;
while (last.next != null) {
last = last.next;
}
last.next = newNode;
}
}
// 删除链表中的第一个元素
public void deleteFirst() {
if (head == null) {
return; // 链表为空,无法删除
}
head = head.next;
}
// 遍历链表
public void display() {
Node current = head;
while (current != null) {
System.out.print(current.data + " -> ");
current = current.next;
}
System.out.println("null");
}
}
使用:
public class Main {
public static void main(String[] args) {
SinglyLinkedList list = new SinglyLinkedList();
// 添加元素
list.addLast(1);
list.addLast(2);
list.addLast(3);
list.addFirst(0);
// 遍历并显示链表
list.display();
// 删除元素
list.deleteFirst();
list.display();
}
}
标签:Node,head,day4,list,next,链表,data From: https://www.cnblogs.com/old-tom/p/18457297