下面是使用Java语言编写的CirDoublyList类,实现循环双链表的深拷贝:
class DoubleNode<T> {
T data;
DoubleNode<T> prev, next;
public DoubleNode(T data) {
this.data = data;
this.prev = null;
this.next = null;
}
}
class CirDoublyList<T> {
private DoubleNode<T> head;
public CirDoublyList() {
head = new DoubleNode<>(null);
head.prev = head;
head.next = head;
}
public CirDoublyList(CirDoublyList<T> list) {
if (list.isEmpty()) {
head = new DoubleNode<>(null);
head.prev = head;
head.next = head;
return;
}
// 创建新的头结点
this.head = new DoubleNode<>(null);
this.head.prev = this.head;
// 复制第一个节点,并设置为头结点的后继节点
DoubleNode<T> newNode = new DoubleNode<>(list.head.next.data);
newNode.prev = this.head;
newNode.next = newNode; // 循环链表只有一个节点时,指向自身
this.head.next = newNode;
// 指针用于遍历原始链表和新链表
DoubleNode<T> p1, p2;
// 使用for循环复制剩余的节点
for (p1 = list.head.next.next, p2=this.head.next; p1 != list.head; p1=p1.next, p2=p2.next) {
newNode = new DoubleNode<>(p1.data); // 复制节点
newNode.prev = p2;
newNode.next = this.head; // 设置为循环链表的尾结点
// 将新节点插入到新链表中
p2.next = newNode;
}
}
public boolean isEmpty() {
return head.next == head;
}
public DoubleNode<T> insert(int i, T x) {
if (x == null)
throw new NullPointerException("x == null");
DoubleNode<T> front = head;
// 寻找插入位置的前驱节点
for (int j = 0; front.next != head && j < i; j++)
front = front.next;
// 创建新节点并插入链表
DoubleNode<T> newNode = new DoubleNode<>(x);
newNode.prev = front;
newNode.next = front.next;
front.next.prev = newNode;
front.next = newNode;
return newNode;
}
public DoubleNode<T> insert(T x) {
if (x == null)
throw new NullPointerException("x == null");
// 创建新节点并插入链表末尾
DoubleNode<T> newNode = new DoubleNode<>(x);
if(isEmpty()){
this.head= new Node(x,null,null);
head.setNext(head);
}else{
node=head.getNext();
while(node.getNext()!=head){
node=node.getNext();
}
node.setNext(new Node(x,node,head));
}
return newNode;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if(isEmpty()) {
sb.append("Empty list");
return sb.toString();
}
node=head.getNext();
while(node!=head){
sb.append(node.getData().toString());
node=node.getNext();
}
return sb.toString();
}
}
public class Main {
public static void main(String[] args) {
CirDoublyList<Integer> list1 = new CirDoublyList<>();
list1.insert(1);
list1.insert(2);
list1.insert(3);
// 测试深拷贝
CirDoublyList<Integer> list2 = new CirDoublyList<>(list1);
System.out.println("原始链表:");
System.out.println(list1.toString());
System.out.println("深拷贝的链表:");
System.out.println(list2.toString());
}
}
运行以上代码,可以验证循环双链表的深拷贝是否正确。
内容由零声教学AI助手提供,问题来源于学员提问




