-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathListNode.java
More file actions
32 lines (30 loc) · 885 Bytes
/
ListNode.java
File metadata and controls
32 lines (30 loc) · 885 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
class Solution {
public ListNode doubleIt(ListNode head) {
head = reverse(head);
ListNode dummy = new ListNode(0), curr = dummy;
int carry = 0;
while (head != null || carry > 0) {
int sum = carry + (head != null ? head.val * 2 : 0);
curr.next = new ListNode(sum % 10);
carry = sum / 10;
curr = curr.next;
if (head != null) head = head.next;
}
return reverse(dummy.next);
}
private ListNode reverse(ListNode head) {
ListNode prev = null, curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
}