1

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.

asked Oct 24, 2018 at 17:27
2
  • Are you trying to use your own implementation of a LinkedList or use the one provided by java? Commented Oct 24, 2018 at 17:29
  • I am given a class: ListNode with int val, ListNode node, and a constructor Commented Oct 24, 2018 at 17:32

2 Answers 2

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.

answered Oct 24, 2018 at 17:34
1
  • Thank you so much! Commented Oct 24, 2018 at 19:01
-1

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;

answered Oct 24, 2018 at 17:55

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.