Leetcode02. Add Two Numbers Medium
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.
Follow up
What if the the digits in the linked list are stored in non-reversed order? For example:
(3 -> 4 -> 2) + (4 -> 6 -> 5) = 8 -> 0 -> 7
提交记录
```java
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int carry = 0;
ListNode dummy = new ListNode(0);
ListNode p = l1, q = l2, cur = dummy;
while (p!=null||q!=null) {
int x = (p != null) ? p.val : 0;
int y = (q != null) ? q.val : 0;
int sum = x + y + carry;
cur.next = new ListNode(sum % 10);
carry = sum / 10;
cur = cur.next;
if(q!=null) q = q.next;
if(p!=null) p = p.next;
}
if(carry == 1)
cur.next = new ListNode(1);
return dummy.next;
}
#### 解法
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200302181154328.jpg)
考虑进位:每一位相加肯定会产生进位,用 carry 表示。进位最大会是 1 ,因为最大的情况是无非是 9 + 9 + 1 = 19 ,也就是两个最大的数相加,再加进位,这样最大是 19 ,不会产生进位 2 。
- 初始化一个节点的头,dummy head ,但是这个头不存储数字。并且将 curr 指向它。
- 初始化进位 carry 为 0 。
- 初始化 p 和 q 分别为给定的两个链表 l1 和 l2 的头,也就是个位。
- 循环,直到 l1 和 l2 全部到达 null 。
- 设置 x 为 p 节点的值,如果 p 已经到达了 null,设置 x 为 0 。
- 设置 y 为 q 节点的值,如果 q 已经到达了 null,设置 y 为 0 。
- 设置 sum = x + y + carry 。
- 更新 carry = sum / 10 。
- 创建一个值为 sum mod 10 的节点,并将 curr 的 next 指向它,同时 curr 指向变为当前的新节点。
- 向前移动 p 和 q 。
- 判断 carry 是否等于 1 ,如果等于 1 ,在链表末尾增加一个为 1 的节点。
- 返回 dummy head 的 next ,也就是个位数开始的地方。
初始化的节点 dummy head 没有存储值,最后返回 dummy head 的 next 。这样的好处是不用单独对 head 进行判断改变值。也就是如果一开始的 head 就是代表个位数,那么开始初始化的时候并不知道它的值是多少,所以还需要在进入循环前单独对它进行值的更正,不能像现在一样只用一个循环简洁。
##### Java
```java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int carry = 0;
ListNode dummy = new ListNode(0);
ListNode p = dummy;
while (l1 != null || l2 != null || carry != 0) {
if (l1 != null) {
carry += l1.val;
l1 = l1.next;
}
if (l2 != null) {
carry += l2.val;
l2 = l2.next;
}
p.next = new ListNode(carry%10);
carry /= 10;
p = p.next;
}
return dummy.next;
}
}
Python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
prenode = ListNode(0)
curnode = prenode
carry = 0
while carry or l1 or l2:
carry, value = divmod(carry + (l1.val if l1 else 0) + (l2.val if l2 else 0), 10)#c,d=divmod(a,b);c=a/b,d=a%b
#后面两行可以写为n.next = n = ListNode(val) ,意思是首先n.next=ListNode(val),然后和n.next指向同一地址。
#n = n.next = ListNode(val)的意思是首先n=ListNode(val),然后n.next指向ListNode(val)的地址,即他们指向同一地址
curnode.next = ListNode(value)
curnode = curnode.next
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
return prenode.next
C++
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {//16ms
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
ListNode preHead(0), *p = &preHead;
int extra = 0;
while (l1 || l2 || extra) {//extra是考虑到两个链表全部遍历完毕后,进位值为1,加到新链表中。
int sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + extra;
extra = sum / 10;
p->next = new ListNode(sum % 10);
p = p->next;
l1 = l1 ? l1->next : l1;
l2 = l2 ? l2->next : l2;
}
return preHead.next;//preHead是对象,而不是指针,所以preHead.next表示其数据成员next(即ListNode指针)
}
};
class Solution {//28ms
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
ListNode preHead(0);
ListNode *p = &preHead;
int extra = 0;
while (l1 || l2 || extra) {
if (l1) {
extra += l1->val;
l1 = l1->next;
}
if (l2) {
extra += l2->val;
l2 = l2->next;
}
p->next = new ListNode(extra % 10);
extra /= 10;
p = p->next;
}
return preHead.next;
}
};
扩展:非逆序
链表先逆序计算,然后将结果再逆序输出
next = head -> next; //保存 head 的 next , 以防取下 head 后丢失
head -> next = pre; //将 head 从原链表取下来,添加到新链表上
pre = head;// pre 右移
head = next; // head 右移
即定义个函数来将原链表逆序:
public ListNode reverseList(ListNode head){
if(head==null) return null;
ListNode pre=null;
ListNode next;
while(head!=null){
next=head.next;
head.next=pre;
pre=head;
head=next;
}
return pre;
}