Im having trouble with a constructor for a linked list. it takes a string and is supposed to create a node for every character.
i get a nullpointerexception everytime i try to print out the list. Does that mean that not even the first node is being created?
below is my node class and the list constructor.
class CharNode {
private char letter;
private CharNode next;
public CharNode(char ch, CharNode link)
{
ch = letter;
link = next;
}
public void setCharacter(char ch)
{
ch = letter;
}
public char getCharacter()
{
return letter;
}
public void setNext(CharNode next)
{
this.next = next;
}
public CharNode getNext()
{
return next;
}
}
and this is my constructor
// constructor from a String
public CharList(String s) {
CharNode newNode = head;
for(int i = 0; i <s.length(); i++)
{
newNode = new CharNode(s.charAt(i), null);
newNode.setNext(newNode);
}
}
am i constructing it correctly?
As pcalcao said,
=assigns the value on the right to the variable on the left. You’ll need to changech = letter;toletter = ch;andlink = next;tonext = link;Now, the line
CharNode newNode = head;doesn’t mean anything unless you’ve specified whatheadis prior to the code you’ve given, but it doesn’t look like it. Remember that when creating a linked list, you don’t start with anything, so even “special” nodes likeheadmust be created (instantiated, if you prefer). The idea is to create the first node (the head), and then assignheadto that first node. For every node after the first one, this step isn’t required, as you simply are adding to the end of the list.Finally, during construction, you’ll need a reference to both a new node (like you have now), and the previous node, in order to do proper appending. Your code now is simply setting the next node in the list to the current node, which means that once you create a new
newNode, you will lose the reference to the previousnewNode.A good way to approach linked lists when one is first getting started is to draw out what you want to do step by step, then try and translate that into code. Hopefully this is helpful.