Friday, January 24, 2014

Add Two Numbers (Java)

LeetCode

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

Solution: use two references point to the head of each list and add them and carry one by one. 
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class AddTwoNumbers {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1==null){
return l2;
}
if (l2==null){
return l1;
}
ListNode preHead=new ListNode(-1);
ListNode end=preHead;
ListNode node1=l1;
ListNode node2=l2;
int carry=0;
while(node1!=null || node2!=null ||carry!=0){
int current=0;
if (node1!=null){
current+=node1.val;
node1=node1.next;
}
if (node2!=null){
current+=node2.val;
node2=node2.next;
}
if (carry!=0){
current+=carry;
}
end.next=new ListNode(current%10);
end=end.next;
carry=current/10;
}
return preHead.next;
}
}

No comments:

Post a Comment