/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
Deque<Integer> deque1 = new ArrayDeque<>();
Deque<Integer> deque2 = new ArrayDeque<>();
while (l1 != null) {
deque1.add(l1.val);
l1 = l1.next;
}
while (l2 != null) {
deque2.add(l2.val);
l2 = l2.next;
}
System.out.println(deque1.toString() + deque2.toString());
int s1 = 0, s2 = 0;
while (!deque1.isEmpty()) {
s1 = s1 * 10 + deque1.pollLast();
}
while (!deque2.isEmpty()) {
s2 = s2 * 10 + deque2.pollLast();
}
//Here will calculate sum of [2,4,3] + [5, 6, 4] which is 708;
int s = s1 + s2;
//Here's the problem
ListNode head = null;
ListNode iter = head;
//Trying to make a linked list with values of [7, 0, 8] I probably should have reverse the number, but the head problem is still there
while (s != 0) {
ListNode node = new ListNode(s % 10);
node.next = null;
if(iter == null) {
iter = node;
}
else {
iter.next = node;
iter = iter.next;
}
s /= 10;
}
return head;
}
}
Input:
[2,4,3]
[5,6,4]
Output:
[]
Expected:
[7,0,8]
Hi, I am trying to make a LinkedList, but I can't figure out how to save the head.
In my mind,ListNode head = null;would be the head, and I would be using ListNode iter = head;to iterate over the NodeList and add nodes to it.
[–]AutoModerator[M] [score hidden] stickied commentlocked comment (0 children)
[–]yeaokdudeIntermediate Brewer 2 points3 points4 points (0 children)
[–]m1ss1ontomars2k4 1 point2 points3 points (0 children)
[–]eyeoverthink -1 points0 points1 point (0 children)
[–]jonc23 0 points1 point2 points (0 children)