I'm trying a standard interview question, which is to add two digits in the form of linkedlists and return the added answer. Here is the question:
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8
342 + 465 = 807 Make sure there are no trailing zeros in the output list So, 7 -> 0 -> 8 -> 0 is not a valid response even though
the value is still 807.
Now, the code I am writing takes in two arguments in the form of ListNode
datatypes which is the starting node of the LinkedLists. What I am not understanding is
- How do I maintain the head node of the list to reference later?
How does call by value and call by reference work in Java? I've dealt with pointers and call by reference in C++ but I've been trying stuff in Java now and it's pretty different.
class ListNode { public int val; public ListNode next; ListNode(int x) { val = x; next = null; } } public class Solution { public ListNode reverse(ListNode head) { ListNode curr = head; ListNode next = null; ListNode prev = null; while (curr != null) { next = curr.next; curr.next = prev; prev = curr; curr = next; } head = prev; return head; } public ListNode addTwoNumbers(ListNode a, ListNode b) { ListNode node = null; ListNode head = null; boolean carry = false; while (a != null || b != null) { int f = 0, s = 0; if (carry) { f++; } carry = false; if (a != null) { f += a.val; a = a.next; } if (b != null) { s = b.val; b = b.next; } if (f + s > 9) { carry = true; } int curr = (f + s) % 10; node = new ListNode(curr); if (head == null) { head = node; } node = node.next; //warning that 'value of node assigned is never used' } if (carry) { node = new ListNode(1); } printList(head); return node; } }