我在一次采访中被问到这个问题,目的是将链表A的元素克隆到一个新的列表中。这是我的方法,但我被拒绝了。我确实做对了,但我不确定为什么面试官不喜欢我的方法。有什么建议/建议可以让我做得更好吗?列表A有元素10,12,11,4,5,6,让我们假设。
public class CopyLinkedListElements {
public static void main(String[] args) {
LinkedList linkedList = new LinkedList();
linkedList.head = new Node(10);
linkedList.head.next = new Node(12);
linkedList.head.next.next = new Node(11);
linkedList.head.next.next.next = new Node(4);
linkedList.head.next.next.next.next = new Node(5);
linkedList.head.next.next.next.next.next = new Node(6);
cloneOrgList(linkedList.head);
}
public static void cloneOrgList(Node head) {
Node current = head;
Node newHead = new Node(current.data);
Node prev = newHead;
System.out.println(prev.data);
while(current != null && current.next != null) {
current = current.next;
Node newNode = new Node(current.data);
prev.next = newNode;
prev = newNode;
System.out.println(prev.data);
}
}
}发布于 2021-03-11 16:09:09
除了前面提到的关于返回值的内容之外,这个循环还有点混乱。它可以像这样改进:
public static Node cloneLinkedList(Node head) {
Node oldCurrent = head;
Node newHead = new Node(oldCurrent.data);
Node newCurrent = newHead;
while ((oldCurrent = oldCurrent.next) != null) {
newCurrent.next = new Node(oldCurrent.data);
newCurrent = newCurrent.next;
}
return newHead;
}发布于 2021-03-11 16:37:40
如果面试官使用“克隆”而不是“复制”这个词,他或她可能想知道您是否知道如何在Java中正确地克隆对象。如果是这样的话,您需要创建一个可克隆的类。基本的方法是实现Cloneable标记接口并覆盖Object的clone方法。
public class MyClass implements Cloneable {
// Details of MyClass omitted
// Because Java supports covariant return types, the return type
// for the overridden clone method is the same as the class (i.e. MyClass)
// Also, the method needs to be made public instead of protected.
@Override
public MyClass clone() {
try {
return (MyClass) super.clone();
} catch (CloneNotSupportedException e) {
throw new AssertionError("Something went wrong. This isn't supposed to happen");
}
}
}如果他或她只是想要一个副本,那么像您展示的方法应该是可以的,除了前面已经提到的:您的函数无法返回副本。因此,从本质上讲,该方法是无用的。
最后,因为你最初的帖子说“克隆链表的元素”,所以你可以调用链表克隆方法
LinkedList<SomeClass> original = new LinkedList<>();
...
LinkedList<SomeClass> clone = (LinkedList<SomeClass>) original.clone();同样,如果面试官希望你复制内容,你可以执行以下操作之一:
Collections.copy(dest, source)dest.addAll(source)List<String> dest = source.stream().collect(Collectors.toList());最后,第三种选择是面试官希望你在Java中克隆和复制对象,在这种情况下,你可以同时演示这两种情况。将来,在开始编码之前,让面试官用你自己的话来澄清和重申问题,以确认你正确理解了问题。从你的代码中,很明显你误解了面试官。
发布于 2021-03-11 15:59:14
您需要克隆该列表,以便返回新的引用和值。这在cloneOrgList方法中不会发生。它不返回任何内容,并且它所操作的节点的作用域仅限于方法本身。
你需要做一些事情,比如
public LinkedList cloneOrgList(LinkedList orig) {
Node origCurr = orig.head;
LinkedList copy = new LinkedList();
Node newCurr = new Node(origCurr.data);
copy.head = newCurr;
while (origCurr.next != null) {
origCurr = origCurr.next;
newCurr.next = new Node(origCurr.data);
newCurr = newCurr.next;
}
return copy;
}https://stackoverflow.com/questions/66578291
复制相似问题