单链表是一种常见的数据结构,它由一系列节点组成,每个节点包含两部分:数据和指向下一个节点的引用。单链表的特点是只能从头到尾进行遍历,不像数组那样可以通过索引直接访问元素。
节点(Node):链表的基本单位,包含数据域和指针域。
头节点(Head):指向链表第一个有效节点的指针。
尾节点(Tail):指向链表最后一个有效节点的指针,其指针域为空(null)。
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
class SinglyLinkedList {
Node head;
// 在链表末尾添加节点
public void append(int data) {
if (head == null) {
head = new Node(data);
return;
}
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = new Node(data);
}
// 在链表头部添加节点
public void prepend(int data) {
Node newNode = new Node(data);
newNode.next = head;
head = newNode;
}
// 删除指定数据的节点
public void delete(int data) {
if (head == null) return;
if (head.data == data) {
head = head.next;
return;
}
Node current = head;
while (current.next != null && current.next.data != data) {
current = current.next;
}
if (current.next != null) {
current.next = current.next.next;
}
}
// 打印链表
public void printList() {
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.append(1);
list.append(2);
list.append(3);
list.prepend(0);
list.printList(); // 输出: 0 -> 1 -> 2 -> 3 -> null
list.delete(2);
list.printList(); // 输出: 0 -> 1 -> 3 -> null
}
}
问题1:链表中的循环引用
问题2:内存泄漏
问题3:性能问题
通过理解这些基础概念和实现细节,可以更好地应用单链表解决实际问题。
领取专属 10元无门槛券
手把手带您无忧上云