1、
Add Two Numbers
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
分析:开始没看懂题意,这中间加法涉及到进位问题,进的位在下一个数体现。而且看题目以为数字以相反的顺序存放,开始写还用了翻转链表,后来测试用例中有问题才发现不需要翻转链表。注意输入链表不一定等长,设置一个进位标志。
如下:
class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
if(!l1){
return l2;
}else if(!l2){
return l1;
}
ListNode* head = NULL;
ListNode* node1 = l1;
ListNode* node2 = l2;
ListNode* preNode = NULL;
int takeOver = 0;
int val = 0;
while(node1 || node2){
if(node1 && node2){
val = node1->val + node2->val+takeOver;
node1 = node1->next;
node2 = node2->next;
}else if(node1){
val = node1->val + takeOver;
node1 = node1->next;
}else if(node2){
val = node2->val + takeOver;
node2 = node2->next;
}
takeOver = val/10;
val %= 10;
ListNode* tempNode = new ListNode(val);
if(!preNode){
head = tempNode;
}else{
preNode->next = tempNode;
}
preNode = tempNode;
}
if(takeOver){
ListNode* tempNode = new ListNode(1);
preNode->next = tempNode;
}
return head;
}
};