将单链表改为循环单链表,只需要在构造方法中将尾节点的next指向头节点即可。下面是修改后的代码:
public class CirSinglyList<T> {
public static void main(String arg[]) {
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<Integer>(value);
CirSinglyList<Integer> list = new CirSinglyList<Integer>(values);
System.out.println(list.toString());
System.out.println(list1.toString());
list.addAll(9, list1);
System.out.println(list.toString());
}
public Node<T> head;
public CirSinglyList() {
this.head = new Node<T>();
}
public CirSinglyList(T[] values) {
this();
Node<T> rear = this.head;
for (int i = 0; i < values.length; i++) {
if (values[i] != null) {
rear.next = new Node<T>(values[i], null);
rear = rear.next;
}
}
// 将尾节点的next指向头节点,形成循环
rear.next = this.head.next;
}
public String toString() {
// 遍历循环链表时,设置一个结束条件(遍历到头节点),以免无限循环输出
if (this.head.next == null) {
return "()";
}
String str = "(";
Node<T> p = this.head.next;
while (p != this.head) {
str += p.data.toString() + (p.next != this.head ? "," : "");
p = p.next;
}
return str + ")";
}
public void addAll(int i, CirSinglyList<T> list) {
Node<T> front = this.head;
Node<T> temp;
Node<T> p = this.head;
for (int j = 0; j < i - 1; j++) {
front = front.next;
}
while (p.next != this.head) {
temp = list.head;
while (temp.next != null) {
if (temp.next.data.equals(p.next.data)) {
temp.next = temp.next.next;
} else
temp = temp.next;
}
p = p.next;
}
// 将list的节点接到链表中
Node<T> tailList1 = list.head;
while (tailList1.next != null && tailList1.next != list.head) {
tailList1 = tailList1.next;
}
tailList1.next = front.next;
}
// 节点类
private static class Node<E> {
E data; // 数据元素
Node<E> next; // 后继节点
public Node() { // 构造指定数据元素和后继节点的结点
this(null, null);
}
public Node(E data, Node<E> next) { // 构造指定数据元素和后继节点的结点
this.data = data;
this.next = next;
}
}
}
在修改后的代码中,添加了一个next字段指向头节点,形成循环链表。同时在toString()方法中遍历链表时,设置了结束条件为遍历到头节点,以防止无限循环输出。
内容由零声教学AI助手提供,问题来源于学员提问




