简体   繁体   English

返回一个新的链表(定制的)

[英]Returning a new LinkedList (custom built)

I am trying to return a new linkedList of numbers after filtering.我试图在过滤后返回一个的数字linkedList What I have here modifies the original list it's invoked on in-place and a toString() on the original list fails afterwards.我在这里修改了它就地调用的原始列表,然后原始列表上的toString()失败。 How do I return a new list without interfering with the original one this method is called on?如何在不干扰调用此方法的原始列表的情况下返回新列表?

public CustomLinkedList filterEvenInts() {
    Node current = data; 
    
    // note: returned list should have values in the order they appeared in the original list.
    
    if (current == null) {
        return new CustomLinkedList();
    }

    Node prev = current;
    while (prev.next != null) {
        if (prev.next.value % 2 != 0) {
            prev.next = prev.next.next;
        } else {
            prev = prev.next;
        }
    }

    // delete current if odd too
    if (current.next.value % 2 != 0) {
        current = current.next;
        prev = current;
    }

    CustomLinkedList newList = new CustomLinkedList();
    newList.data = prev;
    
    return newList;
    
}

From what I understood you would probably have to copy the list somehow first.据我了解,您可能必须先以某种方式复制列表。 Just creating a new one and setting the data of the new one to the old one won't work as you are still referencing the same object. One way to do it would be to go through each node of the old list, create a new node from the value of the old node and add the new node to the new list.仅仅创建一个新的并将新的数据设置为旧的是行不通的,因为您仍然引用相同的 object。一种方法是通过旧列表的每个节点到 go,创建一个新的从旧节点的值中提取节点并将新节点添加到新列表中。 Editing the new list then doesn't affect the old list.编辑新列表不会影响旧列表。

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

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