I have the next classes: (Singly linked list)
public class class CharNode {
private char _value;
private CharNode _next;
public CharNode(char val, CharNode n) {
_value = val;
_next = n;
}
public CharNode(char val) {
_value = val;
_next = null;
}
public int getValue() {
return _value;
}
public CharNode getNext() {
return _next;
}
public void setValue(char v) {
_value = v;
}
public void setNext(CharNode node) {
_next = node;
}
}
and this class:
public class CharList {
private CharNode _head;
public CharList()
{
_head = null;
}
//methods
}
I need to write a method (called "what") that gets two char and returns the amount of possible lists that starts and ends with those char. for example if the linked list is "abbcd" the method what(a,b) will return 2 and the method what(a,c) will return 1. I saw the next solution:
public int what(char start, char end)
{
int count = 0, countStart = 0;
CharNode temp = _head;
while(temp != null)
{
if(temp.getValue() == start){
countStart++;
temp = temp.getNext();
if(temp.getValue() == start && start == end)
countStart++;
}
if(temp.getValue() == end && countStart>0){
count += countStart;
}
temp = temp.getNext();
}
return count;
}
but the problem is that I can't understand how they get the algorithm. In other words, how does it work "mathematical"?