I am trying to make an int (like 123) into a linked list. For example: 123 would result in a linked list of 3 -> 2 -> 1. My issue is that I am able to get each part of the number(like 3 or 2) but I can't seem to make the linked list.
Here is my while Loop:
value = Integer.parseInt(l1StrRev) + Integer.parseInt(l2StrRev);
result = new ListNode(value % 10);
value = value / 10;
while(value > 0) {
int newVal = value % 10;
result.next = new ListNode(newVal);
result = result.next;
value = value / 10;
}
I am getting back a linked-list of just one node with the most recent value.
-
Are you trying to use your own implementation of a LinkedList or use the one provided by java?Nicholas K– Nicholas K2018年10月24日 17:29:50 +00:00Commented Oct 24, 2018 at 17:29
-
I am given a class: ListNode with int val, ListNode node, and a constructorToffe1369– Toffe13692018年10月24日 17:32:25 +00:00Commented Oct 24, 2018 at 17:32
2 Answers 2
In your code, you are updating the "result" variable too. So when u return the "result" variable, its actually pointing to the last Node. I would suggest, before the while loop do a resultCopy = result. And then in the end return resultCopy. This way, resultCopy stores the head node of the list, and "result" acts as a temporary node as in ur code.
-
Thank you so much!Toffe1369– Toffe13692018年10月24日 19:01:56 +00:00Commented Oct 24, 2018 at 19:01
Looks like you are missing and mixed up a couple of lines. In your loop it should be something like...
Create a new node
Node node = new ListNode(newVal);
Set node.next to the result
node.next = result;
Your result then becomes the new node above
result = node;