简体   繁体   中英

Returning a new LinkedList (custom built)

I am trying to return a new linkedList of numbers after filtering. What I have here modifies the original list it's invoked on in-place and a toString() on the original list fails afterwards. 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. Editing the new list then doesn't affect the old list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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