1.原题
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.
2.题意
给定两个非空的链表,代表的是两个整数,从链表头到链表尾代表的是从数的低位到高位。对这两个链表求和,结果也存储在链表里面。
3.思路
- 首先理解链表代表整数,其实这类问题很常见,对于大整数,就是大小可能会超过计算机存储大小的整数,通常会用字符数组,或者数字链表表示。
- 这道题目的难点其实是对链表的判空操作,以及进位
- 粗略思路就是模仿加法法则,每一位两个数字相加,保存进位,下一位两位相加的时候加上进位。
- 需要注意的是,当某个链表已经到达最高位了,比如2->1, 3->2->1,这两个数字相加时,2+3 = 5, 1+ 2 = 3,这时百位上只有第二个链表有值,这时最终结果的百位就是1,最终结果是5->3->1。
- 另外需要注意的是,某个链表已经走到头了,或者两个都到头了,但还是存在进位,比如1, 9->9->9, 1 + 9 = 0,进位是1, 需要将进位1继续与第二个9相加, 最终得到 0->0->0->1
4.代码
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) {
ListNode head = new ListNode(0);
ListNode current = head;
int carry = 0;
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;
}
ListNode node = new ListNode(carry % 10);
carry = carry / 10;
current.next = node;
current = node;
}
return head.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, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
head = ListNode(0)
current = head
carry = 0
while l1 != None or l2 != None or carry != 0:
if l1 != None:
carry += l1.val
l1 = l1.next
if l2 != None:
carry += l2.val
l2 = l2.next
node = ListNode(carry%10)
carry = int(carry/10)
current.next = node
current = node
return head.next