-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdd Two Numbers As Linked List.java
More file actions
71 lines (64 loc) · 1.89 KB
/
Copy pathAdd Two Numbers As Linked List.java
File metadata and controls
71 lines (64 loc) · 1.89 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
import java.util.* ;
import java.io.*;
/****************************************************************
Following is the class structure of the Node class:
class LinkedListNode {
int data;
LinkedListNode next;
public LinkedListNode(int data) {
this.data = data;
}
}
*****************************************************************/
public class Solution {
static LinkedListNode addTwoNumbers(LinkedListNode head1, LinkedListNode head2) {
// Write your code here.
LinkedListNode ans = new LinkedListNode(0);
LinkedListNode temp = ans;
int ext =0;
while(head1!=null && head2!=null && head1.data!=-1 && head2.data!=-1){
int val = head1.data+head2.data+ext;
if(val>=10){
ext = val/10;
val = val%10;
}
else{
ext=0;
}
temp.next = new LinkedListNode(val);
temp = temp.next;
head1 = head1.next;
head2 = head2.next;
}
while(head1!=null && head1.data!=-1){
int val = head1.data+ext;
if(val>=10){
ext = val/10;
val = val%10;
}
else{
ext=0;
}
temp.next = new LinkedListNode(val);
temp = temp.next;
head1 = head1.next;
}
while(head2!=null && head2.data!=-1){
int val = head2.data+ext;
if(val>=10){
ext = val/10;
val = val%10;
}
else{
ext=0;
}
temp.next = new LinkedListNode(val);
temp = temp.next;
head2=head2.next;
}
if(ext!=0){
temp.next = new LinkedListNode(ext);
}
return ans.next;
}
}