Created
May 26, 2019 18:04
-
-
Save madhur/06efc0c156ef67b695d803eef75a6675 to your computer and use it in GitHub Desktop.
Add two linkedlist
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static ListNode sumTwoLinkedLists(ListNode input1, ListNode input2) { | |
int carryComponent =0; | |
ListNode returnHead = new ListNode(0); | |
ListNode n1 = input1, n2 = input2, n3=returnHead; | |
while(n1 != null || n2 != null){ | |
if(n1 != null){ | |
carryComponent += n1.data; | |
n1 = n1.next; | |
} | |
if(n2 != null){ | |
carryComponent += n2.data; | |
n2 = n2.next; | |
} | |
n3.next = new ListNode(carryComponent%10); | |
n3 = n3.next; | |
carryComponent /= 10; | |
} | |
if(carryComponent==1) | |
n3.next=new ListNode(1); | |
return returnHead.next; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment