描述
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.
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头
例子

思路
- 错误的
把两个链表中的数字先取出来得到整数,相加得到总数,再用链表表示:链表可以很长,c++中int,long都不能表示(python可以)
- 正确的
两个链表看成长度相同的相加,短的链表后面每位补0,链表第一位表示个位,相加,保留%10的值,将/10的整数传给第二位相加,如果其中一个链表的该位为空,则取值为0,如果两个链表都进行到空结点了,但进位jinwei>0则,表示还有最后一个结点
789+56=789+560=反(987+065)=反(1043)=3401
答案
- java
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int jin = 0;
ListNode h = new ListNode(-1),cur=h;
while(l1!=null || l2!=null) {
int a = l1==null?0:l1.val;
int b = l2==null?0:l2.val;
int v = (a+b+jin)%10;
cur.next=new ListNode(v);
cur=cur.next;
l1=l1==null?l1:l1.next;
l2=l2==null?l2:l2.next;
jin = (a+b+jin)/10;
}
if(jin!=0)
cur.next = new ListNode(jin);
return h.next;
}
}
- python
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
head = ListNode(0)
cur = head
jinwei = 0
while (l1 or l2 or jinwei):
n = (l1.val if l1 else 0)+(l2.val if l2 else 0)+jinwei
jinwei = int(n/10)
cur.next = ListNode(n%10)
cur = cur.next
l1 = l1.next if l1 else l1
l2 = l2.next if l2 else l2
return head.next
- c++
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
ListNode* addTwoNumbers(ListNode* L1, ListNode* L2) {
ListNode* head = new ListNode(0);
ListNode* cur = head;
int jinwei =0;
while (L1 || L2 || jinwei)
{
int n = (L1?L1->val:0)+(L2?L2->val:0)+jinwei;
cur->next = new ListNode(n%10);
cur = cur->next;
jinwei = n/10;
L1 = L1?L1->next:L1;
L2 = L2?L2->next:L2;
}
return head->next;
}
链表加法
560

被折叠的 条评论
为什么被折叠?



