两个数字相加(我最不会的链表)
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.
ListNode的定义
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
除了进位之外,考虑链表的长度。L1和L2的长度。
- 两个一样长
- L1比较长
- L2比较长
C++版本。
自己的版本。
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *head = l1;
int flag=0;
while(l1!=NULL){
//l1 end
if(l1->next==NULL&&l2->next!=NULL){
l1->next = l2->next;
l2->next = NULL;
}
int tmp = l1->val + l2->val +flag;
flag = (tmp<10)?0:1;
l1->val = tmp%10;
//all end
if(l2->next==NULL&&l1->next==NULL&&flag){
l1->next = new ListNode(1);
flag=2;
break;
}
//l2 end
if(l2->next==NULL){
break;
}
l1 = l1->next;
l2 = l2->next;
}
l1=l1->next;
while(l1&&flag!=2){
int tmp = l1->val+flag;
flag = (tmp<10)?0:1;
l1->val = tmp%10;
if(l1->next==NULL&&flag) {
l1->next=new ListNode(1);
break;
}
l1 = l1->next;
}
return head;
}
网上找的另一个版本。
ListNode* addTwoNumbers(ListNode* l1,ListNode* l2){
ListNode *head = l1;
int flag = 0;
while(l1!=NULL &&l2!=NULL){
int tmp = l1->val +l2->val +flag;
flag = (tmp<10)?0:1;
l1->val = tmp%10;
//把短的补0
if(l1->next==NULL&&l2->next!=NULL){
l1->next = new ListNode(0);
}else if (l1->next!=NULL&&l2->next==NULL){
l2->next = new ListNode(0);
}
//如果结束了
if(l1->next==NULL &&l2->next==NULL &&flag==1){
l1->next = new ListNode(1);
break;
}else{
l1 = l1->next;
l2 = l2->next;
}
}
return head;
}