-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnextno.java
More file actions
84 lines (59 loc) · 1.49 KB
/
Copy pathnextno.java
File metadata and controls
84 lines (59 loc) · 1.49 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
74
75
76
77
78
79
80
81
82
83
84
package linkedlist;
class node {
int data;
node next;
node prev;
public node(int data) {
this.data = data;
this.next = null;
this.prev = null;
}
}
public class nextno {
public static node reverse(node head) {
if (head == null || head.next == null) {
return head;
}
node curr = head;
node prev = null, fwd = null;
while (curr != null) {
fwd = curr.next;
curr.next = prev;
prev = curr;
curr = fwd;
}
head = prev;
return head;
}
public static node nextnumber(node head) {
node rev = reverse(head);
int carry = 1;
node temp = rev;
node prev = null;
while (temp != null) {
int sum = (temp.data + carry) % 10;
carry = (temp.data + carry) / 10;
temp.data = sum;
prev = temp;
temp = temp.next;
}
if (carry > 0) {
node newnode = new node(carry);
prev.next = newnode;
prev = newnode;
}
return reverse(rev);
}
public static void main(String[] args) {
node one = new node(3);
node two = new node(7);
one.next = two;
node head = one;
node ans = nextnumber(head);
node temp = ans;
while (temp != null) {
System.out.print(temp.data + "->");
temp = temp.next;
}
}
}