下面是改错后的代码,已添加了addAll方法、concat方法和union方法:
public class CirDoublyList<T> {
public DoubleNode<T> head;
public DoubleNode<T> rear;
public CirDoublyList() {
this.head = new DoubleNode<T>();
this.head.prev = this.head;
this.head.next = this.head;
}
public String toString() {
StringBuilder str = new StringBuilder(this.getClass().getName() + "(");
for (DoubleNode<T> p = this.head.next; p != this.head; p = p.next)
str.append(p.data.toString()).append(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 CirDoublyList(DoublyList<T> list) {
this();
DoubleNode<T> rear = this.head;
while (rear.next != null)
rear = rear.next;
rear.next = list.head.next;
if (list.head.next != null) {
list.head.next.prev=rear;//新增
list.rear=null;//新增
// 修改原来的代码:
// 将list尾节点指向空,避免形成闭环
// while(rear.next!=null)
// rear=rear.next;
// list.rear= rear ;
// 修改原来的代码:
// 将list尾节点prev指向head,实现闭环
// if(list.rear!=null)
// list.rear.prev=head;
}
}
public void concat(DoublyList<T> list) {
if (list.head.next != null) {
this.rear.next = list.head.next;
list.head.next.prev = this.rear;
// 修改原来的代码:
// 将this尾节点指向list尾节点
while(this.rear.next!=null)
this.rear=this.rear.next;
// this.rear=list.rear;
// 修改原来的代码:
// 将list尾节点指向head,实现闭环
// if(list.rear!=null)
// list.rear.prev=head;
list.head.next=null;//新增
list.rear=null;//新增
}
}
public void addAll(DoublyList<T> list) {
this.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) {
DoublyList<Integer> list1 = new DoublyList<>();
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());
CirDoublyList<Integer> cirList1 = new CirDoublyList<>(list1);
cirList1.addAll(list2);
System.out.println(cirList1.toString());
CirDoublyList<Integer> cirList2 = new CirDoublyList<>(list1);
CirDoublyList<Integer> unionList = cirList2.union(list2);
System.out.println(unionList.toString());
}
}
注意:在改错的过程中,根据原始代码的逻辑进行了修改,并补充了一些额外的操作以确保正确性。
内容由零声教学AI助手提供,问题来源于学员提问