0% found this document useful (0 votes)
43 views1 page

Add Two Numbers in Linked Lists

The document defines a Java class for adding two numbers represented by singly-linked lists. It includes a method that iterates through both lists, calculates the sum of corresponding digits along with any carry, and constructs a new linked list to represent the result. The method returns the head of the new linked list after processing all digits and carry.

Uploaded by

wedok26771
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views1 page

Add Two Numbers in Linked Lists

The document defines a Java class for adding two numbers represented by singly-linked lists. It includes a method that iterates through both lists, calculates the sum of corresponding digits along with any carry, and constructs a new linked list to represent the result. The method returns the head of the new linked list after processing all digits and carry.

Uploaded by

wedok26771
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

/**

* Definition for singly-linked list.


* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { [Link] = val; }
* ListNode(int val, ListNode next) { [Link] = val; [Link] = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
// solution
// step 1: define two new node dymmy and temp
// step 2: define carry as variable and assign the value as 0
// step 3: iiterate the while loop upto l1 is not null or l2 is not null or
carray equals to 1
// step 4: inside the loop define the sum variable and initalize it as 0
// step 5: check l1 is null or not if not null the add [Link] in sum and
push l1 next
// step 6: check l2 is null or not if not null then add [Link] in sum and
push l2 next
// step 7: add the carry into sum;
// step 8: calculate carry by deviding the sum by 10
// step 9: create the new node with the the value of sum of modulo 10
// step 10: [Link] to that new node
// step 11: incease temp to [Link]
// step 12: after the loop retrun the [Link]

ListNode dummy= new ListNode();


ListNode temp=dummy;
int carry=0;

while(l1!=null || l2!=null || carry==1){


int sum=0;
if(l1!=null){
sum=[Link];
l1=[Link];
}

if(l2!=null){
sum+=[Link];
l2=[Link];
}

sum+=carry;
carry=sum/10;
ListNode node= new ListNode(sum%10);
[Link]=node;
temp=[Link];
}
return [Link];
}
}

You might also like