Skip to content
Advertisement

Why is this intersection method in the doubly circular linked list not working? [closed]

public static DCLL inter(DCLL a, DCLL b) {
        Element curA = a.head;
        DCLL c = new DCLL();
        
        if(a.head == null || b.head == null)
            return c;
        
        while(curA != a.rear) {
            if(b.isInList(curA.data)) {
                c.insert(curA.data);
                curA = curA.next;
                c.length++;
            }
        }
        return c;
    }

This is the intersection method where I should return a list that contains all the same elements in list a and b, but the program is looping infinitely and the only while loop in this method can loop infinitely, so I’m not getting why it’s not working.

The isInList() and insert() methods works perfectly fine.

I updated my code and I think it will work but now I’m getting another error in the toString method in the line s = " | " + cur.data + " | ";. It’s a null pointer exception but why is it an error?

        String s = " ";
        if(this.isEmpty())
            return"Empty list";
        
        Element cur = this.head;
        s = " | " + cur.data + " | ";
        cur = cur.next;
        while(cur != this.head) {
            s+= cur.data + " | ";
            cur = cur.next;
        }
        return s;
    }  

Advertisement

Answer

You are not updating your currA in case b.isInList(curA.data) is false. Therefore you again and again check whether “curA != a.rear” and this will not change.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement