-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathp171.java
109 lines (90 loc) · 2.83 KB
/
p171.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
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
102
103
104
105
106
107
108
109
/*Given two decimal numbers represented by two linked lists of size N and M respectively. The task is to return a linked list that represents the sum of these two numbers.
For example, the number 190 will be represented by the linked list, 1->9->0->null, similarly 25 by 2->5->null. Sum of these two numbers is 190 + 25 = 215, which will be represented by 2->1->5->null. You are required to return the head of the linked list 2->1->5->null.
Example 1:
Input:
N = 2
valueN[] = {4,5}
M = 3
valueM[] = {3,4,5}
Output: 3 9 0
Explanation: For the given two linked
list (4 5) and (3 4 5), after adding
the two linked list resultant linked
list will be (3 9 0).
Example 2:
Input:
N = 2
valueN[] = {6,3}
M = 1
valueM[] = {7}
Output: 7 0
Explanation: For the given two linked
list (6 3) and (7), after adding the
two linked list resultant linked list
will be (7 0).
Your Task:
The task is to complete the function addTwoLists() which has node reference of both the linked lists and returns the head of the sum list.
Expected Time Complexity: O(N+M)
Expected Auxiliary Space: O(Max(N,M)) for the resultant list.
Constraints:
1 <= N, M <= 5000*/
/* node for linked list
class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}*/
class Solution {
static Node addTwoLists(Node first, Node second) {
// Reverse both input linked lists
first = reverseLinkedList(first);
second = reverseLinkedList(second);
int carry = 0;
int sum = 0;
Node result = null;
Node current = null;
while (first != null || second != null) {
int firstVal = (first != null) ? first.data : 0;
int secondVal = (second != null) ? second.data : 0;
sum = carry + firstVal + secondVal;
carry = sum / 10;
int digit = sum % 10;
Node newNode = new Node(digit);
if (result == null) {
result = newNode;
current = newNode;
} else {
current.next = newNode;
current = newNode;
}
if (first != null) {
first = first.next;
}
if (second != null) {
second = second.next;
}
}
if (carry > 0) {
Node carryNode = new Node(carry);
current.next = carryNode;
}
// Reverse the result linked list
result = reverseLinkedList(result);
return result;
}
public static Node reverseLinkedList(Node head) {
Node current = head;
Node previous = null;
Node next = null;
while (current != null) {
next = current.next;
current.next = previous;
previous = current;
current = next;
}
return previous;
}
}