以下是使用Java语言编写的CirDoublyList类,包含了for循环,insert方法,CirDoublyList()构造函数,toString()方法,isEmpty()方法以及验证所需的main函数。
public class CirDoublyList<T> {
private DoubleNode<T> head;
public CirDoublyList() {
head = new DoubleNode<>();
head.prev = head;
head.next = head;
}
public CirDoublyList(CirDoublyList<T> list) {
this();
for (DoubleNode<T> p = list.head.next; p != list.head; p = p.next) {
insert(p.data);
}
}
public void insert(T x) {
DoubleNode<T> newNode = new DoubleNode<>(x, head, head.next);
newNode.prev.next = newNode;
newNode.next.prev = newNode;
}
public DoubleNode<T> insert(int i, T x) {
if (i < 0)
throw new IndexOutOfBoundsException("Index " + i + " is negative");
int j = 0;
DoubleNode<T> p = head;
while (p.next != head && j < i) {
p = p.next;
j++;
}
if (j != i)
throw new IndexOutOfBoundsException("Index " + i + " is out of bounds");
DoubleNode<T> newNode = new DoubleNode<>(x, p, p.next);
newNode.prev.next = newNode;
newNode.next.prev = newNode;
return newNode;
}
public boolean isEmpty() {
return head == null || head.next == null || head.prev == null ||
head == head.prev && head == head.next &&
head.data == null && head.prev.data == null && head.next.data == null;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
if (!isEmpty()) {
DoubleNode<T> p = head.next;
while (p != head) {
sb.append(p.data);
if (p.next != head)
sb.append(", ");
p = p.next;
}
}
sb.append("]");
return sb.toString();
}
public static void main(String[] args) {
CirDoublyList<Integer> list1 = new CirDoublyList<>();
for (int i = 1; i <= 5; i++) {
list1.insert(i);
}
System.out.println("Original List: " + list1);
CirDoublyList<Integer> list2 = new CirDoublyList<>(list1);
System.out.println("Copied List: " + list2);
}
}
class DoubleNode<T> {
T data;
DoubleNode<T> prev, next;
public DoubleNode() {
this(null, null, null);
}
public DoubleNode(T data, DoubleNode<T> prev, DoubleNode<T> next) {
this.data = data;
this.prev = prev;
this.next = next;
}
}
这段代码定义了一个CirDoublyList类,它是一个循环双链表。在main函数中,我们创建了一个原始列表list1,并使用for循环插入了1到5的整数。然后通过调用构造函数复制了一个新的列表list2。最后,我们打印出原始列表和复制列表的内容。
希望这能满足你的需求!
内容由零声教学AI助手提供,问题来源于学员提问




