[Solved] Problems with linked list


You should not create nodes outside of set. When you do

c1.insert(n1);

at first this code executes

if (isEmpty()) {
    first = r;
    previousIP = first;
    IP = previousIP.next;
    size++;
}

which is holding in first and previousIP current node, which is node stored also by n1. But when you execute later

c1.insert(n2);

since c1 is no longer empty else part is executed

} else if (!belongs(r)) {
    previousIP.next = r;
    previousIP = previousIP.next;
    IP = previousIP.next;
    size++;
}

which is setting previousIP.next to r and since previous holds same object as reference n1 and r as n2 you are effectively setting n1.next=n2.

Finally you are adding n1 to your second set n2 with

c2.insert(n1);

but this means you are adding n1 which is already internally pointing to n2. That is why both c1 and c2 seem to contain same structure.

What you should be doing to is rewrite your insert method in a way that will internally create its own independent RationalNodes. So your code should not be focused on accepting RationalNodes but Rationals like

public void insert(Rational r) {
    if (isEmpty()) {
        first = new RationalNode(r);//changed
        previousIP = first;
        IP = previousIP.next;
        size++;
    } else if (!belongs(r)) {
        previousIP.next = new RationalNode(r);//changed
        previousIP = previousIP.next;
        IP = previousIP.next;
        size++;
    }
}

You will also need to redesign rest of your code which handles RationalNode to handle Rational.

BTW, you can make your RationalNode private inner class in RationalSet. This way say more explicitly that instance of this class should be created only by RationalSet and must belong to one of its instances.

0

solved Problems with linked list