-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTest5-Next Number
83 lines (75 loc) · 1.65 KB
/
Test5-Next Number
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
77
78
79
80
81
82
83
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
***********************************Solution******************************************
public class Solution {
public static LinkedListNode<Integer> nextLargeNumber(LinkedListNode<Integer> head) {
LinkedListNode<Integer> temp;
LinkedListNode<Integer> prev= null;
LinkedListNode<Integer> curr= head;
while(curr!=null)
{
temp=curr.next;
curr.next=prev;
prev=curr;
curr=temp;
}
LinkedListNode<Integer> tem=prev;
int cnt=0;
LinkedListNode<Integer> a=new LinkedListNode<>(1);
while(tem!=null)
{
if(tem.data==9)
{
tem.data=0;
cnt=1;
if(tem.next==null)
tem.next=a;
}
else
{
if(cnt==1)
{
int d=tem.data+1;
if(d==10)
{
tem.data=0;
cnt=1;
}
else{
cnt=0;
}
}
else{
tem.data=tem.data+1;
break;
}
}
tem=tem.next;
}
LinkedListNode<Integer> temp1;
LinkedListNode<Integer> prev1=null;
LinkedListNode<Integer> curr1=prev;
while(curr1!=null)
{
temp1=curr1.next;
curr1.next=prev1;
prev1=curr1;
curr1=temp1;
}
return prev1;
}
}