我正在尝试以与克隆单数链表相同的方式克隆循环链表,但遇到了麻烦。
我试图在公共方法clone()中只留下调用受保护方法clone()的行,但程序仍然抛出错误。
public static void main(String[] args) throws CloneNotSupportedException
{
CircularlyLinkedList<String> circularList = new
CircularlyLinkedList<String>();
circularList.addFirst("1");
circularList.addLast("2");
circularList.addLast("3");
circularList.addLast("4");
CircularlyLinkedList<String> newList = new CircularlyLinkedList<String>();
newList= circularList.clone();
System.out.println(newList);
}
@SuppressWarnings("unchecked")
public CircularlyLinkedList<E> clone() throws CloneNotSupportedException
{
// always use inherited Object.clone() to create the initial copy
CircularlyLinkedList<E> other = (CircularlyLinkedList<E>) super.clone(); // safe cast
if (size > 0) { // we need independent chain of nodes
other.head = new Node<>(head.getElement(), null);
Node<E> walk = head.getNext(); // walk through remainder of original list
Node<E> otherTail = other.head; // remember most recently created node
while (walk != null) { // make a new node storing same element
Node<E> newest = new Node<>(walk.getElement(), null);
otherTail.setNext(newest); // link previous node to this one
otherTail = newest;
walk = walk.getNext();
}
}
return other;
}
此代码在使用单链表时有效。预期的输出是打印两次的链表,但实际输出的是抛出的异常“CloneNotSupported”。请注意,当 clone() 返回空列表时,程序不会抛出此异常。
智慧大石
相关分类