user2909869
user2909869

Reputation: 125

Concatenating 2 Linked Lists - Java

I am having some trouble with NullPointExceptions when attempting to concatenate two linked lists in JAVA.

The code for main to test it is:

d1 = new MyDeque ();
d2 = new MyDeque ();
d2.pushLeft (11);
d1.concat (d2);

While the code for the concat function is:

public void concat (MyDeque that) {

    if (!that.isEmpty())
    {
        this.last.next = that.first;
        this.N += that.N;

        that.first = null;
        that.last = null;
        that.N = 0;
    }
}

The portion that I don't understand is that it flags NullPointerException. "d2" or that isn't empty, and "d1" is, which sort of makes me understand that there would be a null value, "d1", pointing to the first value in "d2", aka 11, with this.last.next = that.first. Should I make another statement that handles this differently if "d1" is empty as well?

Upvotes: 0

Views: 968

Answers (2)

oliver
oliver

Reputation: 2833

Make sure you are checking that the next node is not empty

while (list.next != null)

Is the standard approach, it may be slightly different if you are using a custom end token

Upvotes: 0

La-comadreja
La-comadreja

Reputation: 5755

Although I don't have your entire node class, I see 2 possible places for you to have a NullPointerException.

(1)

if (!that.isEmpty())

You should verify (that != null). Your code will throw a NullPointerException if that is null.

(2)

this.last.next = that.first;

Your code will throw a NullPointerException if this.last is null. Make sure it isn't, or check beforehand.

Upvotes: 1

Related Questions