Reputation: 49
I have created this Node class for a singly linked list:
class Node{
int item;
Node next;
Node(int v){
item = v;
next = null;
}
}

I want to make a search for the node with the highest key in a method called findmax.But i want to check if the list is empty, and if so , to return null, otherwise return the node with the highest key. This is what i have done:
Node findmax(Node h){
if(h==null)
return null;
else{
//search
}
All i want to know is if the check i make to see if the list is Empty is correct.
Upvotes: 2
Views: 10045
Reputation: 920
Yes, the check you've done is correct if:
Node n = null;// init empty list
and:
n = new Node(3);// first item
However, I suggest you to create a list
struct which is independent from the item
it concatenates. That's what I mean:
The Node
class:
public class Node
{
int value;
public Node(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
The list
struct:
public interface IList
{
public int getNodeNumbers();
}
public class EmptyList implements IList
{
@Override public int getNodeNumbers() {
return 0;
}
}
public class ConsList implements IList
{
private Node node;
private IList next;
public ConsList(Node node, IList next) {
this.node = node;
this.next = next;
}
@Override public int getNodeNumbers() {
return 1 + next.getNodeNumbers();
}
}
How to use it:
public class Main
{
public static void main(String[] args) {
IList list1 = new ConsList(new Node(1),
new ConsList(new Node(2),
new ConsList(new Node(3),
new ConsList(new Node(4),
new EmptyList()))));
IList list2 = new EmptyList();
System.out.println(list1.getNodeNumbers() + " - " + list2.getNodeNumbers());
}
}
And now, a list is empty (you can create your own method isEmpty()
into the IList
interface) when getNodeNumbers()
returns 0.
Upvotes: 0