I need help filling in the last method public class NodeList { private int size
ID: 3800043 • Letter: I
Question
I need help filling in the last method
public class NodeList {
private int size = 0;
private Node root = null;
/*
* It has to take a new Node and add that to the next address of previous
* Node. If the list is empty, assign it as the "root"
*
* @Param - Node
*/
public void add(Node node) {
if (node == null)
return;
if (root == null)
root = node;
else {
Node temp = root;
while (temp.next != null) {
temp = temp.next;
}
temp.next = node;
}
}
/*
* It has to return the size of the NodeList
*
* @return size
*/
public int size() {
int count = 0;
if (root == null)
return count;
else {
Node temp = root;
while (temp != null) {
temp = temp.next;
count++;
}
size = count;
}
return size;
}
/*
* It has to take a Node and checks if the node is in the list. If it finds
* the node, it returns true, otherwise false
*
* @param - Node
*
* @return boolean true/false
*/
public boolean findNode(Node node) {
}
}
Explanation / Answer
Faced a confusion : Whether to match the node itself or the value of it ? So created the solution for both.
First solution, matching the nodes.
public boolean findNode(Node node) {
if (node == null)
return false;
if (root == null)
return false;
else
{
Node temp = root;
while (temp.next != null)
{
if(temp == node)
{
return true;
}
temp = temp.next;
}
return false;
}
}
Second solution, matching the values,
public boolean findNode(Node node) {
if (node == null)
return false;
if (root == null)
return false;
else
{
Node temp = root;
while (temp.next != null)
{
if(temp.value == node.value)
{
return true;
}
temp = temp.next;
}
return false;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.