Java的链表类是LinkedList,它是一个双向链表,可以用于实现List和Deque接口,提供了插入、删除、遍历等操作。Java的链表是一种线性数据结构,由一系列节点组成,每个节点包含一个数据元素和一个指向下一个节点的指针,链表可以分为单向链表、双向链表和循环链表等类型。
单向链表
单向链表是最简单的链表类型,每个节点只有一个指向下一个节点的指针。下面是一个简单的单向链表实现:
```java
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
Node head;
public void add(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 display() {
Node current = head;
while (current != null) {
System.out.print(current.data + " > ");
current = current.next;
}
System.out.println("null");
}
}
```
双向链表
双向链表与单向链表类似,但每个节点有两个指针,一个指向前一个节点,一个指向后一个节点。下面是一个简单的双向链表实现:
```java
class DoublyNode {
int data;
DoublyNode prev;
DoublyNode next;
public DoublyNode(int data) {
this.data = data;
this.prev = null;
this.next = null;
}
}
class DoublyLinkedList {
DoublyNode head;
DoublyNode tail;
public void add(int data) {
DoublyNode newNode = new DoublyNode(data);
if (head == null) {
head = newNode;
tail = newNode;
} else {
tail.next = newNode;
newNode.prev = tail;
tail = newNode;
}
}
public void display() {
DoublyNode current = head;
while (current != null) {
System.out.print(current.data + " <> ");
current = current.next;
}
System.out.println("null");
}
}
```
循环链表
循环链表是一种特殊的链表,它的最后一个节点的指针指向第一个节点,形成一个环。下面是一个简单的循环链表实现:
```java
class CircularDoublyNode {
int data;
CircularDoublyNode prev;
CircularDoublyNode next;
public CircularDoublyNode(int data) {
this.data = data;
this.prev = null;
this.next = null;
}
}
class CircularDoublyLinkedList {
CircularDoublyNode head;
CircularDoublyNode tail;
public void add(int data) {
CircularDoublyNode newNode = new CircularDoublyNode(data);
if (head == null) {
head = newNode;
tail = newNode;
head.next = head;
tail.next = head;
} else {
tail.next = newNode;
newNode.prev = tail;
tail = newNode;
tail.next = head;
head.prev = tail;
}
}
public void display() {
CircularDoublyNode current = head;
do {
System.out.print(current.data + " <> ");
current = current.next;
} while (current != head);
System.out.println("null");
}
}
```
总结
通过这篇文章,我们介绍了Java链表的三种类型:单向链表、双向链表和循环链表,以及它们的实现方式。使用链表可以方便地在任意位置插入和删除元素,但要注意链表的指针操作,以及链表节点的申请和释放,避免出现内存泄漏等问题。
本文链接:https://www.24zzc.com/news/171692846275279.html