|
发表于 2023-11-13 10:21:01
|
显示全部楼层
[/code]java
public class CircularLinkedList<T> {
private Node<T> head;
private int size;
// 构造函数
public CircularLinkedList() {
head = null;
size = 0;
}
// 结点类
private static class Node<T> {
T data;
Node<T> next;
Node(T data, Node<T> next) {
this.data = data;
this.next = next;
}
}
// 插入新的结点
public void insert(T data) {
if (head == null) {
head = new Node<>(data, null);
head.next = head; // 单结点成环
} else {
Node<T> newNode = new Node<>(data, head.next);
head.next = newNode;
}
size++;
}
// 删除指定元素结点
public void delete(T data) {
if (head != null) {
Node<T> current = head;
while (current.next != head && !current.next.data.equals(data)) {
current = current.next;
}
if (current.next.data.equals(data)) {
current.next = current.next.next;
size--;
}
}
}
// 查找指定元素结点
public boolean search(T data) {
Node<T> current = head;
do {
if (current.data.equals(data)) {
return true;
}
current = current.next;
} while (current != head);
return false;
}
// 修改指定位置结点
public void modify(int position, T newData) {
if (position < 0 || position >= size) {
throw new IndexOutOfBoundsException("Invalid position");
}
Node<T> current = head;
for (int i = 0; i < position; i++) {
current = current.next;
}
current.data = newData;
}
// 遍历循环链表
public void traverse() {
Node<T> current = head;
do {
System.out.print(current.data + " ");
current = current.next;
} while (current != head);
System.out.println();
}
// 测试类
public static void main(String[] args) {
CircularLinkedList<Integer> list = new CircularLinkedList<>();
list.insert(1);
list.insert(2);
list.insert(3);
list.traverse(); // 输出:3 2 1
list.delete(2);
list.traverse(); // 输出:3 1
System.out.println(list.search(3)); // 输出:true
list.modify(1, 4);
list.traverse(); // 输出:3 4
}
}
[/code] |
|