-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaddnoLLrecursion.java
More file actions
101 lines (81 loc) · 2.54 KB
/
addnoLLrecursion.java
File metadata and controls
101 lines (81 loc) · 2.54 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
class ListNode {
int value;
ListNode next;
}
class GFG {
// To store the carry
private static int carry = 0;
// Function that calls the recursive method
// addNewValue to add a digit to the
// number represented as the linked list
public static ListNode addValue(ListNode head, int addValue)
{
// Add the digit recursively
addNewValue(head, addValue);
// If there is a carry after the addition
if (carry != 0) {
// Create a new node
ListNode newHead = new ListNode();
// Assign it with carry
newHead.value = carry;
// Make it point to the head of
// the linked list
newHead.next = head;
carry = 0;
// Make it the new head
return newHead;
}
// If there's not carry then
// return the previous head
else {
return head;
}
}
// Recursive function to add a digit to the number
// represented as the given linked list
private static void addNewValue(ListNode head, int addValue)
{
// If it is the last node in the list
if (head.next == null) {
// Add the digit
int val = head.value + addValue;
// Find the carry if any
head.value = val % 10;
carry = val / 10;
}
else {
// Preserve the current node's value and call
// the recursive function for the next node
int val = head.value;
addNewValue(head.next, addValue);
val = val + carry;
head.value = val % 10;
carry = val / 10;
}
}
// Utility function to print the linked list
private static void printList(ListNode node)
{
while (node != null) {
System.out.print(node.value + " -> ");
node = node.next;
}
System.out.print("NULL");
}
// Driver code
public static void main(String[] args)
{
// Create the linked list 9 -> 9 -> 3 -> NULL
ListNode head = new ListNode();
head.value = 9;
head.next = new ListNode();
head.next.value = 9;
head.next.next = new ListNode();
head.next.next.value = 3;
head.next.next.next = null;
// Digit to be added
int n = 7;
head = addValue(head, n);
printList(head);
}
}