11. Implement the following method as a new static method for the IntNode class.
ID: 3816690 • Letter: 1
Question
11. Implement the following method as a new static method for the IntNode class. (Use the usual Node definition with instance variables called data and link.) public static boolean dataIsOn(IntNode head, IntNode p) // Precondition: head is the head reference of a linked list // (which might be empty, or might be non-empty). The parameter p // is a non-null reference to some IntNode on some linked list. // Postcondition: The return value is true if the data in p // appears somewhere in a data field of a node in head's // linked list. Otherwise the return value is false. // None of the nodes on any lists are changed.
Explanation / Answer
public static boolean dataIsOn(IntNode head, IntNode p) {
// Precondition: head is the head reference of a linked list
// (which might be empty, or might be non-empty). The parameter p
// is a non-null reference to some IntNode on some linked list.
// Postcondition: The return value is true if the data in p
// appears somewhere in a data field of a node in head's
// linked list. Otherwise the return value is false.
// None of the nodes on any lists are changed.
// traversing through linked list
while(head != null){
if(head.data == p.data) // if found p, then return true
return true;
head = head.link;
}
return false; // not found
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.