单链表Java代码实现
时间: 2023-10-19 07:08:29 浏览: 82
Java单链表的实现代码
public class LinkedList {
private Node head;
private class Node {
int data;
Node next;
Node(int data) {
this.data = data;
next = null;
}
}
public void add(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
return;
}
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = 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 printList() {
Node current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
}
}
阅读全文