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 contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example 1:
Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.
Example 2:Input: l1 = [0], l2 = [0]
Output: [0]
Example 3:Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]
Constraints:
The number of nodes in each linked list is in the range [1, 100].
0 <= Node.val <= 9
It is guaranteed that the list represents a number that does not have leading zeros.来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题目大意:
要你将两个链表中存储的数字加起来,并形成一个新的链表。
实现思路:
这道题的实现思路有好几种,我看到其中一种是直接对其中一个链表进行操作,这样毫无疑问可以节省空间。我采用的是另一种方法,新建一个链表,将加起来得到的数字存入其中。
实现代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
void attach(int a,ListNode** t){
ListNode* tmp=new ListNode;
tmp->val=a;
tmp->next=NULL;
(*t)->next=tmp;
(*t)=(*t)->next;
}
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* t1=l1;
ListNode* t2=l2;
ListNode* p=new ListNode;
p->next=NULL;
ListNode* rear=p;
int plus=0;
int sum;
while(t1&&t2){
sum=plus+t1->val+t2->val;
plus=sum/10;
sum=sum%10;
attach(sum,&rear);
t1=t1->next;
t2=t2->next;
}
while(t1){
sum=plus+t1->val;
plus=sum/10;
sum=sum%10;
attach(sum,&rear);
t1=t1->next;
}
while(t2){
sum=plus+t2->val;
plus=sum/10;
sum=sum%10;
attach(sum,&rear);
t2=t2->next;
}
if(plus) attach(1,&rear);
ListNode* t=p;
p=p->next;
delete t;
return p;
}
};
这里注意三点:
1、尽量用new在生成一个结点,我最初用malloc一直报错,改成new就可以了。
2、每个指针负责各自的功能,不要混用,不然你也不知道会出现什么问题,比如一开始我在末尾释放内存的时候用rear指针指向旧的p,最终似乎形成了一个环。。。。所以,指针各司其职,不要混用。
3、这里用三目运算符应该可以节省不少代码量,我写的相对比较烦。