Reputation: 76
i have a linked list and i need to write a method to take an input as a string and check all the elements in the linked list for a match, the method has to return the number of matches.
The problem is that i need to refer to the current linked list without taking it as an input into the method.
public int count(E elem)
{
int count;
for (E list : x)
{
if(this.removeAtHead().equals(elem))
{
count++;
}
else{}
}
return count;
}
i need to replace x with the current linked list.
An example of using the method is:
public static void main(String[ ] args)
{
LinkedList<String> first = new LinkedList<String>();
first.insertAtTail("abc");
first.insertAtTail("def");
first.insertAtTail("def");
first.insertAtTail("xyz");
System.out.println( first.count("def") ); // prints "2"
first.insertAtTail(null);
first.insertAtTail("def");
first.insertAtTail(null);
System.out.println( first.count("def") ); // prints "3"
System.out.println( first.count(null) ); // prints "2"
}
Upvotes: 0
Views: 127
Reputation: 55619
Just make it for (E list : this)
, as follows:
public int count(E elem)
{
int count;
for (E list : this)
{
if (removeAtHead().equals(elem))
{
count++;
}
}
return count;
}
Upvotes: 1
Reputation: 104
Could you create a private variable within your class that contains a List/or list of lists(should you need to keep track of multiple lists). You could then reference the list within other functions of this class or use getters and setters.
Upvotes: 0