带尾指针的单向循环链表java代码
时间: 2024-09-08 10:04:24 浏览: 69
带尾指针的单向循环链表是一种数据结构,它包含一个链表的尾节点,可以快速进行插入和删除操作。以下是一个简单的Java实现示例:
```java
public class CircularLinkedList<T> {
private Node<T> head;
private Node<T> tail;
private static class Node<T> {
T data;
Node<T> next;
Node(T data) {
this.data = data;
}
}
public CircularLinkedList() {
head = null;
tail = null;
}
public void add(T data) {
Node<T> newNode = new Node<>(data);
if (tail == null) {
head = newNode;
newNode.next = head;
tail = newNode;
} else {
tail.next = newNode;
newNode.next = head;
tail = newNode;
}
}
public void remove(T data) {
if (tail == null) return;
Node<T> current = head;
Node<T> previous = tail;
do {
if (current.data.equals(data)) {
if (current == head && current == tail) {
head = null;
tail = null;
} else if (current == head) {
head = current.next;
tail.next = head;
} else if (current == tail) {
tail = previous;
tail.next = head;
} else {
previous.next = current.next;
}
return;
}
previous = current;
current = current.next;
} while (current != head);
}
public void display() {
if (tail == null) return;
Node<T> current = head;
do {
System.out.print(current.data + " ");
current = current.next;
} while (current != head);
System.out.println();
}
}
```
在上面的代码中,`CircularLinkedList` 类定义了一个带尾指针的单向循环链表。它提供了添加(`add`)、删除(`remove`)和显示链表内容(`display`)的基本操作。`Node` 类是内部静态类,用于表示链表的节点。
阅读全文