26.1k views
4 votes
Suppose you have a linked list composed of Nodes:

public class Node {
public Node next;
public E data;
}
Write an iterative method boolean contains(Node node, int e) that returns true if and only if the list starting at node contains the given integer.

1 Answer

2 votes

Final answer:

To check if a linked list starting at a given node contains a specific integer, we can use an iterative approach.

Step-by-step explanation:

To check if a linked list starting at a given node contains a specific integer, we can use an iterative approach. We can start from the given node and traverse the linked list until we find the integer or reach the end of the list. Here's an example of how the code for the method would look:

public boolean contains(Node node, int e) {
Node current = node;
while (current != null) {
if (current.data == e) {
return true;
}
current = current.next;
}
return false;
}

In this method, we start from the given node and iterate through the linked list by updating the 'current' node to the next node in each iteration. If we find a node with the given integer, we return true. If we reach the end of the list without finding the integer, we return false.

User Hvollmeier
by
8.5k points