LeetCode 2. Add Two Numbers

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.

实现思路:

题意是将两个链表的数值倒过来进行相加,然后再倒过来依次存储在一个新链表中返回,三个注意点:
1.因为数据的低位在链表的靠近头指针处,将两个链表逐个对应的结点相加即可
2.可能有一个链表更短,所以补齐方式,数字12和34567相加则补齐'0'变成00012,这里的操作方式就是当一个链表指针为空指针的时候用0进行相加即可。
3.链表插入采用后插法。

AC代码:

class Solution {
	public:
		ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
			int res=0;
			ListNode *root=NULL,*p=NULL;
			while(l1||l2) {
				int a=(l1==NULL?0:l1->val);//链表为空了 则用0进行相加 
				int b=(l2==NULL?0:l2->val);
				ListNode *now=new ListNode;
				now->val=(a+b+res)%10;
				now->next=NULL;
				if(p==NULL) {//这是第一个结点的情况 
					p=now;
					root=p;
				} else {//不是第一个结点插入的情况 
					p->next=now;
					p=now;
				}
				res=(a+b+res)/10;
				if(l1!=NULL) l1=l1->next;
				if(l2!=NULL) l2=l2->next;
			}
			if(res!=0)
				p->next=new ListNode(res,NULL);
			return root;
		}
};
posted @ 2021-02-27 17:30  coderJ_ONE  阅读(55)  评论(0编辑  收藏  举报