Carey Brown wrote:On line 35 you are creating a new Node and then later creating another of the same node on line 50.
Line 43 declares a local Node reference variable "current". On line 50 you assign a new Node reference to current. On line 55 current goes out of scope and disappears.
Carey Brown wrote:Two things would help you here. One is to get out pencil and paper and draw the links in the list as you follow the code. Do exactly what the code does and not what you THINK it does. Anther thing might be peppering your code with print statements to follow the paths.
Carey Brown wrote:Do you know what it means for variables to have "scope"? "current", as you've declared it has local scope to the add() method. Once the add() method finishes the variable disappears.
Carey Brown wrote:
Micheal Bush wrote:
Carey Brown wrote:
this method does not add second element. Why do you print current? its always null (from where you add print statement) I know I assign current = new Node(node.data); is not right, it makes current point to this new Node but not head object anymore.
Carey Brown wrote:So, one node adds ok, which is done on line 39. The second node does not add. On line 43 you set current to reference the same node as head. Head is not null at this point so now current has a reference to the first node you added. On line 45 you test current and at this point it is not equal to null. So execute line 47. Current.next is null because our list at this point is only one link long. So now current is null. Back to line 45 but this time current is null so jump to line 52. Now create a new Node and assign the reference to current. Line 56 increments size. Line 57 ends method so current, which is a local variable, is discarded as is the new Node that it refers to. Poof! Gone! Nowhere are you adding the new Node to the "next" of the first node.
Carey Brown wrote:Part of your problem is this
by the time it is equal to null it's too late you've already lost the reference to the last node in the list.
Carey Brown wrote:Forget the code for a minute. Can you describe in English how you'd do this with pencil and paper?
No, Carey is helping you to solve your problem.Micheal Bush wrote:. . . No offence, man, you need at least try to solve my problem instead of teaching me how to read code.
Micheal Bush wrote:Can you solve it??
Micheal Bush wrote:No, man, that is not problem, problem is I assign a object to a new object, so it can not update the original one.
Don't get me started about those stupid light bulbs. |