forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_369.java
58 lines (51 loc) · 1.83 KB
/
_369.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
package com.fishercoder.solutions;
import com.fishercoder.common.classes.ListNode;
public class _369 {
public static class Solution1 {
public ListNode plusOne(ListNode head) {
//get the length of the list and take out the value of each node and store them into an array
ListNode temp = head;
int len = 0;
while (temp != null) {
len++;
temp = temp.next;
}
int[] nums = new int[len];
temp = head;
int j = 0;
while (temp != null) {
nums[j++] = temp.val;
temp = temp.next;
}
//plus one into this array: nums
for (int i = len - 1; i >= 0; i--) {
if (nums[i] != 9) {
nums[i]++;
break;
} else {
nums[i] = 0;
}
}
//still assuming the first value in the list should not be zero as it's representing a valid number, although it's in a list
ListNode pre = new ListNode(-1);
if (nums[0] == 0) {
//in this case, let's just construct a new linked list and return: only first node value is 1, all the rest is 0
ListNode newHead = new ListNode(1);
ListNode result = newHead;
int count = 0;
while (count++ < len) {
newHead.next = new ListNode(0);
newHead = newHead.next;
}
return result;
} else {
pre.next = head;
for (int i = 0; i < len; i++) {
head.val = nums[i];
head = head.next;
}
return pre.next;
}
}
}
}