You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
题目读了半天,简单总结一下:两个非空链表代表两个非负整数,并且数字是倒序存放的,每个节点仅有一个数码。把两个数加起来,以链表形式返回。
看了看....这不就是两个大整数相加的题么,换了个链表的马甲。。。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
#define null NULL
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
if(l1 == NULL && l2 == null ){
return null;
}
int ans = 0;
ListNode *head = null;
ListNode *tail = null;
while(l1 != null || l2 != null){
if(l1 != null){
ans += l1->val;
l1 = l1->next;
}
if(l2 != null){
ans += l2->val;
l2 = l2->next;
}
ListNode *p = new ListNode(ans%10);
ans /= 10;
if(head == NULL){
head = p;
tail = p;
}else{
tail->next = p;
tail = tail->next;
}
}
if(ans!=0){
ListNode *p = new ListNode(ans);
tail->next = p;
tail = tail->next;
}
return head;
}
};