-
Notifications
You must be signed in to change notification settings - Fork 21
/
369. Plus One Linked List.java
executable file
·76 lines (62 loc) · 1.77 KB
/
369. Plus One Linked List.java
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
M
tags: Linked List
time: O(n)
space: O(1)
#### Reverse to make significant digit at tail
- Need add from the back and calculate carry
- Reverse list, so insignificant digit at head; calculate carry
- Reverse back when output
```
/*
Given a non-negative integer represented as non-empty a singly linked list of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.
Example :
Input: [1,2,3]
Output: [1,2,4]
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
/*
Head: 1, 2, 3
- Need add from the back and calculate carry
- Reverse list, so head: 3,2,1; add from head and carry down
- Reverse back when output
*/
class Solution {
public ListNode plusOne(ListNode head) {
ListNode reversedHead = reverse(head);
int carry = 1;
ListNode node = reversedHead;
while (node != null && carry != 0) {
int sum = node.val + carry;
node.val = sum % 10;
carry = sum / 10;
node = node.next;
}
node = reverse(reversedHead);
if (carry > 0) {
ListNode temp = node;
node = new ListNode(carry);
node.next = temp;
}
return node;
}
private ListNode reverse(ListNode node) {
ListNode dummy = new ListNode(0);
while(node != null) {
ListNode temp = node.next;
node.next = dummy.next;
dummy.next = node;
node = temp;// move pointer
}
return dummy.next;
}
}
```