Skip to content

Instantly share code, notes, and snippets.

@madhur
Created May 26, 2019 18:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madhur/06efc0c156ef67b695d803eef75a6675 to your computer and use it in GitHub Desktop.
Save madhur/06efc0c156ef67b695d803eef75a6675 to your computer and use it in GitHub Desktop.
Add two linkedlist
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