Hey everyone, I'm working on a constructor for an assignment for class, and I've ran into a little bit of trouble. I'm working on a copy constructor, and this is what I have so far...
Although I thought this was correct, unfortunately, it is not. I'm getting a null pointer exception because after the setNext() line, I'm trying to access the next, which is null, and I haven't thought of a way to get around this yet. So while trying to figure a way around it, I've tried to work on it recursively, but I'm getting an error when trying to print it, and this is what I've tried recursively...
And thats where I'm stuck, lol..Any suggestions to either of the two codes posted above would be helpful, thanks! (Although I would prefer a solution to the iterative solution, a recursive solution wouldn't bother me either..
Thanks!
Code:
public CharList(CharList l) {
CharNode pt = head;
CharNode pt2 = l.head;
while(pt2.getNext() != null) {
pt.setNext(new CharNode(pt2.getCharacter(), null));
pt = pt.getNext();
pt2 = pt2.getNext();
}
head = pt;
}
Although I thought this was correct, unfortunately, it is not. I'm getting a null pointer exception because after the setNext() line, I'm trying to access the next, which is null, and I haven't thought of a way to get around this yet. So while trying to figure a way around it, I've tried to work on it recursively, but I'm getting an error when trying to print it, and this is what I've tried recursively...
Code:
public CharList(CharList l) {
CharNode pt = l.head;
CharNode pt2 = head;
if(pt == null) {
pt2.setNext(new CharNode(pt.getCharacter(), null));
} else {
pt = pt.getNext();
}
head = pt2;
}
And thats where I'm stuck, lol..Any suggestions to either of the two codes posted above would be helpful, thanks! (Although I would prefer a solution to the iterative solution, a recursive solution wouldn't bother me either..
Thanks!