Skip to content

Instantly share code, notes, and snippets.

@sreeprasad
Created September 24, 2014 11:04
Show Gist options
  • Save sreeprasad/01dc8fd760d9597bced2 to your computer and use it in GitHub Desktop.
Save sreeprasad/01dc8fd760d9597bced2 to your computer and use it in GitHub Desktop.
Adding Two LinkedList Numbers
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if(l1==null){
return l2;
}else if(l2==null){
return l1;
}
ListNode p1=l1,p2=l2,newHead = new ListNode(0);
ListNode p3 = newHead;
int carry=0;
while( p1!=null || p2!=null ){
if(p1!=null){
carry+=p1.val;
p1=p1.next;
}
if(p2!=null){
carry+=p2.val;
p2=p2.next;
}
p3.next = new ListNode(carry%10);
p3=p3.next;
carry/=10;
}
if(carry==1){
p3.next = new ListNode(1);
}
return newHead.next;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment