简体   繁体   English

将linkedlist的元素克隆到新列表

[英]Clone elements of linkedlist to a new list

I was asked this question in an interview to clone the elements of linked list A into a new list.我在一次采访中被问到这个问题,将链表 A 的元素克隆到一个新列表中。 This was my approach but I was rejected.这是我的方法,但我被拒绝了。 I did get it right but I am not sure why the interviewer didn't like my approach.我确实做对了,但我不确定为什么面试官不喜欢我的方法。 Any tips/advise to what I could have done better?关于我可以做得更好的任何提示/建议? List A has elements [10,12,11,4,5,6] let's assume.列表 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);
        }
    }
}

In addition to what was mentioned about return values, the loop is a bit messy.除了提到的返回值之外,循环有点混乱。 It can be improved like this:可以这样改进:

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;
}

If the interviewer used the word "clone" and not "copy" he or she might have wanted to know if you know how to properly clone objects in Java.如果面试官使用“克隆”而不是“复制”这个词,他或她可能想知道您是否知道如何正确克隆 Java 中的对象。 IF that was the case, you needed to create a cloneable class.如果是这种情况,您需要创建一个可克隆的 class。 The basic recipe for this is to implement the Cloneable marker interface and override Object's clone method.基本方法是实现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");
        }
    }
}

If he or she just wanted a copy, an approach like the one you showed should've been OK, except for what has been already mentioned: Your function failed to return the copy.如果他或她只是想要一份副本,那么像您展示的方法应该没问题,除了已经提到的:您的 function 未能返回副本。 So, in essence, the method is useless.因此,从本质上讲,该方法是无用的。

Lastly, since your original post stated "clone the elements of linked list", you could've done call Linked List clone method最后,由于您的原始帖子声明“克隆链表的元素”,因此您可以调用 Linked List 克隆方法

LinkedList<SomeClass> original = new LinkedList<>();
...
LinkedList<SomeClass> clone = (LinkedList<SomeClass>) original.clone();

Again, if the interviewer wanted you to copy the contents, you could've done one of the following:同样,如果面试官希望您复制内容,您可以执行以下操作之一:

  1. Collections.copy(dest, source)
  2. dest.addAll(source)
  3. List<String> dest = source.stream().collect(Collectors.toList());

Lastly, the third alternative was the interviewer wanted you to get into cloning vs copying objects in Java, in which case you would've demonstrated both.最后,第三种选择是面试官希望你进入克隆与复制 Java 中的对象,在这种情况下你会证明两者。 In the future, ask the interviewer to clarify and restate the question in your own words to get confirmation that you understood the question correctly BEFORE you jump into coding.以后,在开始编码之前,请面试官用你自己的话澄清和重述问题,以确认你正确理解了这个问题。 From your code, it is clear you misunderstood the interviewer.从你的代码中,很明显你误解了面试官。

You need to clone the list such that new references and values are returned.您需要克隆列表,以便返回新的引用和值。 This is not happening in the cloneOrgList method.这在cloneOrgList方法中没有发生。 It doesn't return anything and the scope of the node it operates on is limited to the method itself.它不返回任何内容,并且它所操作的节点的 scope 仅限于方法本身。

You need to do something like你需要做类似的事情

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;
}

I think He was expecting to use the clone() method.我认为他希望使用 clone() 方法。

Please have a look at the official doc.请看官方文档。 Javadoc Javadoc

Sample Code:示例代码:

package com.raushan.testmind;

import java.util.LinkedList;

public class TestMain {
    public static void main(String args[]) {

        // Creating an empty LinkedList
        LinkedList<Integer> list = new LinkedList<Integer>();

        // Use add() method to add elements in the list
        list.add(10);
        list.add(12);
        list.add(11);
        list.add(4);
        list.add(5);
        list.add(6);

        // Displaying the list
        System.out.println("First LinkedList:" + list);

        // Creating another linked list and copying
        LinkedList sec_list = new LinkedList();
        sec_list = (LinkedList) list.clone();

        // Displaying the other linked list
        System.out.println("Second LinkedList is:" + sec_list);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM