mail@pastecode.io avatar
a year ago
1.5 kB
Next, we want to check whether a list satisfies certain properties. We call a list valid if:

it does not contain two consecutive red nodes, and
the labels of green nodes are non-decreasing.

Complete the class HeadNode so that it extends the class GreenNode and implements the interface IHeadNode. In particular, the method boolean validList() should check whether the list is valid, according to the above definition.   

    public boolean validList() {
        Node currentNode = getNext();
        Node nextNode = currentNode.getNext();
            if (currentNode instanceof RedNode && nextNode instanceof RedNode) {
                return false;
            else if (currentNode instanceof GreenNode) {
                while (nextNode.getNext() != null && !(nextNode instanceof GreenNode)) {
                    nextNode = nextNode.getNext();
                if (nextNode != null && currentNode.getLabel() < nextNode.getLabel()) {
                    return false;
        return true;

gives error
org.opentest4j.AssertionFailedError: failure of isValid() for list |Green:2|Red:4|Green:1|Red:3| ==] expected: [false] but was: [true]
 at ex2.ValidListTest.testIsValid(ValidListTest.java:60)
 at ex2.ValidListTest.testIsValid(ValidListTest.java:54)
 at java.base/java.util.ArrayList.forEach(Unknown Source)
 at java.base/java.util.ArrayList.forEach(Unknown Source)