-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathNext Number
More file actions
73 lines (62 loc) · 1.45 KB
/
Next Number
File metadata and controls
73 lines (62 loc) · 1.45 KB
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
Next Number
Send Feedback
Given a large number represented in the form of a linked list. Write code to increment the number by 1 in-place(i.e. without using extra space).
Note: You don't need to print the elements, just update the elements and return the head of updated LL.
Input Constraints:
1 <= Length of Linked List <=10^6.
Input format :
Line 1 : Linked list elements (separated by space and terminated by -1)
Output Format :
Line 1: Updated linked list elements
Sample Input 1 :
3 9 2 5 -1
Sample Output 1 :
3 9 2 6
Sample Input 2 :
9 9 9 -1
Sample Output 1 :
1 0 0 0
code in java ********************************************************
public class Solution
{
public static LinkedListNode < Integer > nextLargeNumber (LinkedListNode <
Integer > n)
{
if (n == null)
return n;
LinkedListNode < Integer > current = n;
LinkedListNode < Integer > prev = null;
int length = 0;
LinkedListNode < Integer > last = current;
while (current != null)
{
length++;
if (current.data != 9)
prev = current;
last = current;
current = current.next;
}
if (prev == null)
{
LinkedListNode < Integer > head = new LinkedListNode < Integer > (1);
head.next = n;
while (n != null)
{
n.data = 0;
n = n.next;
}
return head;
}
else
{
prev.data = prev.data + 1;
prev = prev.next;
while (prev != null)
{
prev.data = 0;
prev = prev.next;
}
return n;
}
}
}