1

I have been breaking my head with below code which I made. The problem is that when I do tail.child = null; it is also making my childPoint's child as null. tail is instance variable with below definition:

public List tail;
public void removeMultiLinkList() {
    List headPoint = head;
    while (headPoint.next != null) {
        List childPoint = headPoint;
        while (childPoint.child != null) {
            tail.next = childPoint.child;
            tail = tail.next;
            tail.child=null;
            childPoint = childPoint.child;
        }
        headPoint = headPoint.next;
    }
}

I have made this method to solve the problem of multilevel link list and convert it into linear singly link by in non recurssive manner

2
  • 1
    By @Jeremy : Can you show us the List class you are using? Commented Jan 4, 2015 at 10:17
  • Also, I assume head is also an instance variable? Commented Jan 4, 2015 at 10:20

1 Answer 1

2

Examine what you are doing:

tail.next = childPoint.child; 
tail = tail.next;

In here, tail is childPoint.child (reference identity)

Then, you do:

tail.child=null;

This means, you actually set childPoint.child.child = null; - because chilePoint.child and tail are different names for the same object.

And then, you assign:

childPoint = childPoint.child;

But you assign childPoint to the same object you just changed - so the new childPoint's child, is null!


A very easy workaround is to copy by value (by creating a copy constructor) the elements from one list to the other.

An alternative might be to keep copying references - but without changing child at all. At the end of your algorithm, do some post-processing and set e.child = null for each element e in your list.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.