forked from ved09dev/Hacktoberfest-2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
add nodes in linked list.txt
44 lines (44 loc) · 1.13 KB
/
add nodes in linked list.txt
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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if(l1==null) return l2;
if(l2==null) return l1;
ListNode c1=l1;
ListNode c2=l2;
ListNode dummy = new ListNode(-1);
ListNode temp=dummy;
int carry=0;
while(c1!=null)
{
int d=c1.val+(c2 != null ? c2.val : 0)+carry;
temp.next=new ListNode(d%10);
temp=temp.next;
carry=d/10;
c1=c1.next;
if(c2!=null) c2=c2.next;
}
while(c2!=null)
{
int d=c2.val+carry;
temp.next=new ListNode(d%10);
temp=temp.next;
carry=d/10;
c2=c2.next;
}
if(carry!=0)
{
temp.next=new ListNode(carry);
temp=temp.next;
}
return (dummy.next);
}
}