以下是修改后的代码:
public class CirDoublyList<T> {
public DoubleNode<T> head;
public DoubleNode<T> rear;
public CirDoublyList() {
this.head = new DoubleNode<>();
this.head.prev = this.head;
this.head.next = this.head;
}
public String toString() {
String str = this.getClass().getName() + "(";
for (DoubleNode<T> p = this.head.next; p != this.head; p = p.next)
str += p.data.toString() + (p.next != this.head ? "," : "");
return str + ")";
}
public DoubleNode<T> insert(T x) {
if (x == null)
return null;
DoubleNode<T> q = new DoubleNode<>(x, head.prev, head);
head.prev.next = q;
head.prev = q;
return q;
}
public void concat(CirDoublyList<T> list) {
DoubleNode<T> rear = this.head;
while (rear.next != this.head)
rear = rear.next;
rear.next = list.head.next;
list.head.next.prev = rear;
rear = list.head;
// 恢复list的空表状态
list.head.prev = list.head;
list.head.next= list.head;
// 将rear指向当前链表尾节点
while (rear.next != rear)
rear=rear.next;
// 连接原链表尾和新链表头
rear.next=this.head;
this.rear=rear;//更新尾节点
}
public void addAll(CirDoublyList<T> list) {
concat(list);
}
public CirDoublyList<T> union(DoublyList<T> list) {
CirDoublyList<T> result = new CirDoublyList<>(this);
result.addAll(list);
return result;
}
public static void main(String[] args) {
CirDoublyList<Integer> list1 = new CirDoublyList<>();
DoublyList<Integer> list2 = new DoublyList<>();
for (int i = 1; i <= 5; i++)
list1.insert(i);
for (int i = 6; i <= 10; i++)
list2.insert(i);
System.out.println(list1.toString());
System.out.println(list2.toString());
list1.addAll(list2);
System.out.println(list1.toString());
}
}
在上面的代码中,我们为循环双链表类添加了 concat、addAll 和 union 方法。其中:
concat方法将另一个循环双链表连接到当前链表的末尾,并更新尾节点。addAll方法是concat的别名,将另一个循环双链表连接到当前链表的末尾,并更新尾节点。union方法返回两个链表的并集,在原有链表基础上添加新的元素。
希望以上修改满足你的需求。
内容由零声教学AI助手提供,问题来源于学员提问




