Jeffrey Dilley Jeffrey Dilley - 24 days ago 6
Java Question

LinkList, Checking for double values

I'm writing a code that returns true if the entire link list is stuttered and false if it's not. A stuttered list would be

1,1,2,2,5,5,8,8
, non-stuttered would be something like
1,1,2,2,5,6,8,8
.

I have been playing around with it for quite a while, and can't seem to get it to return the correct statement OR not get a nullpointer exception.

public boolean foo(){
ListNode current = front;
ListNode runner = current.next;
while (current.next.next!=null){ //Looks two ahead for the end
if(current.data!=runner.data){ //They aren't equal, false
System.out.println(current.data); //just to see my data
System.out.println(runner.data); //debugging only
return false;
}
current = current.next.next; //increase by 2
runner = runner.next.next; // increase by 2
System.out.println(current.data + " ||" + runner.data); //again debugging
}
return true; // didn't register false, go ahead and true dat badboy.
}


public static void main (String[] args){
LinkedIntList list = new LinkedIntList();
list.add(1);
list.add(1);
list.add(3);
list.add(3);
list.add(5);
list.add(5);
System.out.println(list.foo());
}


Does someone see an obvious error here? I've tried running my while loop for current.next, as well as increasing my runner and current by one each time instead of two but none of it has worked.

Answer

Instead of while (current.next.next!=null), check while (runner.next!=null)

Assuming the list has an even number of elements, the following code might help. You have to also check for the last condition after the while loop.

public boolean foo(){
    ListNode current = front;
    ListNode runner = current.next;
    while (runner.next!=null){   //Looks two ahead for the end
        if(current.data!=runner.data){      //They aren't equal, false
            System.out.println(current.data); //just to see my data
            System.out.println(runner.data);  //debugging only
            return false;
        }
        current = current.next.next; //increase by 2
        runner = runner.next.next;   // increase by 2
        System.out.println(current.data + " ||" + runner.data); //again debugging
    }
    if(current.data!=runner.data){      //They aren't equal, false
        System.out.println(current.data); //just to see my data
        System.out.println(runner.data);  //debugging only
        return false;
    }
    return true; // didn't register false, go ahead and true dat badboy.
}
Comments