java单链表的实现方法
问题描述:java单链表的实现方法
推荐答案 本回答由问问达人推荐
在Java中,单链表是一种常见的数据结构,用于存储一系列具有相同类型的元素。单链表由一系列节点组成,每个节点包含一个数据元素和一个指向下一个节点的引用。以下是Java中单链表的实现及其基本操作:
节点类的定义:
javaCopy codeclass Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
单链表类的定义:
javaCopy codeclass LinkedList {
private Node head;
public LinkedList() {
this.head = null;
}
// 在链表尾部添加节点
public void append(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 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) {
if (current.next.data == data) {
current.next = current.next.next;
return;
}
current = current.next;
}
}
// 遍历并打印链表元素
public void print() {
Node current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
}
}