以下是改进后的循环单链表的实现:
public class CirSinglyList<T> {
public static void main(String[] args) {
Integer[] values = new Integer[10];
for (int i = 0; i < values.length; i++) {
values[i] = i + 1;
}
Integer[] value = new Integer[10];
for (int j = 0; j < value.length; j++) {
value[j] = j + 6;
}
CirSinglyList<Integer> list1 = new CirSinglyList<>(value);
CirSinglyList<Integer> list = new CirSinglyList<>(values);
System.out.println(list.toString());
System.out.println(list1.toString());
list.addAll(9, list1);
System.out.println(list.toString());
}
private Node<T> head;
public CirSinglyList() {
this.head = new Node<>();
}
public CirSinglyList(T[] values) {
this();
if (values != null && values.length > 0) {
Node<T> rear = this.head;
for (T value : values) {
if (value != null) {
rear.next = new Node<>(value, null);
rear = rear.next;
}
}
rear.next = this.head.next; // 构建循环链表
}
}
public String toString() {
String str="(";
if(this.head.next == null)
return "()";
Node<T> p=this.head.next;
while(p != this.head){
str += p.data.toString() + ",";
p=p.next;
}
str=str.substring(0,str.length()-1); // 去除最后一个逗号
str += ")";
return str;
}
public void addAll(int i, CirSinglyList<T> list) {
if (list.head.next == null) {
return; // 如果要添加的链表为空,则直接返回
}
Node<T> front = this.head;
Node<T> p = this.head.next;
for (int j = 0; j < i; j++) {
front = front.next;
p = p.next;
if (p == this.head) {
break; // 超出链表长度,直接退出循环
}
}
Node<T> temp = list.head.next;
while (temp != null) {
if (!contains(p, temp.data)) {
temp = temp.next;
} else {
break; // 在目标链表中找到重复元素,跳出循环
}
}
front.next = list.head.next;
while (temp != null) {
if (!contains(p, temp.data)){
p.next=temp;
p=p.next;
}
temp=temp.next;
if(temp==list.head)
break;
}
p.next=this.head; // 构建循环链表
}
private boolean contains(Node<T> node, T data) {
Node<T> p=node;
while(p != this.head){
if(p.data.equals(data))
return true;
p=p.next;
if(p == node)
break;
}
return false;
}
private static class Node<E>{
private E data;
private Node<E> next;
public Node() {}
public Node(E data, Node<E> next) {
this.data = data;
this.next = next;
}
}
}
这是一个改进后的循环单链表实现,重写了toString()方法以正确输出循环链表中的元素。同时在addAll()方法中实现了避免添加重复元素,并构建循环链表的逻辑。
内容由零声教学AI助手提供,问题来源于学员提问




