leetcode 2. Add Two Numbers
It's really tired after a whole day's work and a phone interview after work.
So I decided to relax and end today with a nice and easy and two numbers.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int rest = 0;
ListNode head = new ListNode(0);
ListNode ptr = head;
while (l1 != null || l2 != null) {
int val = rest;
if (l1 != null) {
val += l1.val;
l1 = l1.next;
}
if (l2 != null) {
val += l2.val;
l2 = l2.next;
}
ptr.next = new ListNode(val % 10);
rest = val / 10;
ptr = ptr.next;
}
if (rest != 0) ptr.next = new ListNode(rest);
return head.next;
}
}