12. Implement the following method as a new static method for the IntNode class.
ID: 3816693 • Letter: 1
Question
12. 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 isOn(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 p actually points to // one of the IntNodes in the head's linked list. For example, // p might point to the head node of this list, or the second node, // or the third node, and so on. Otherwise the return value is // false. None of the nodes on any lists are changed.
Explanation / Answer
public static boolean isOn(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 p actually points to
// one of the IntNodes in the head's linked list. For example,
// p might point to the head node of this list, or the second node,
// or the third node, and so on. Otherwise the return value is
// false. None of the nodes on any lists are changed.
// traversing through linked list
while(head != null){
if(head == p) // p points to link in list
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.