问题描述
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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Solution
Intuition
Keep track of the carry using a variable and simulate digits-by-digits sum starting from the head of list, which contains the least-significant digit.
Algorithm
Just like how you would sum two numbers on a piece of paper, we begin by summing the least-significant digits, which is the head of l1 and l2. Since each digit is in the range of 0 …9, summing two digits may “overflow”. For example 5 + 7 = 12. In this case, we set the current digit to 2 and bring over the carry = 1 to the next iteration. carry must be either 0 or 1 because the largest possible sum of two digits (including the carry) is 9 + 9 + 1 = 19.
The pseudocode is as following:
- Initialize current node to dummy head of the returning list.
- Initialize carry to 0.
- Initialize p and q to head of l1 and l2 respectively.
- Loop through lists l1 and l2 until you reach both ends.
- Set x to node p’s value. If p has reached the end of l1, set to 0.
- Set y to node q’s value. If q has reached the end of l2, set to 0.
- Set sum = x + y + carry.
- Update carry = sum / 10.
- Create a new node with the digit value of (sum mod 10) and set it to current node’s next, then advance current node to next.
- Advance both p and q.
- Check if carry = 1, if so append a new node with digit 1 to the returning list.
- Return dummy head’s next node.
Note that we use a dummy head to simplify the code. Without a dummy head, you would have to write extra conditional statements to initialize the head’s value.
Take extra caution of the following cases:
我的解决方法之C
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode* dummyHead = (struct ListNode*)malloc(sizeof(struct ListNode)),*p=l1,*q=l2;//给结果线性表定义虚拟头结点
dummyHead->val =0;//初始化虚拟头结点的值为空值
dummyHead->next=NULL;//初始化只有一个结点
struct ListNode* curr = dummyHead;//将当前结点初始化为返回列表dummyHead的虚拟头结点
int carry = 0;//存储进位
while(p!=NULL || q!=NULL){
int x = (p != NULL) ? p->val : 0;
int y = (q != NULL) ? q->val : 0;
int sum = carry+x+y;
carry =sum/10;
curr->next = (struct ListNode*)malloc(sizeof(struct ListNode));
curr->next->val=sum%10;
curr->next->next=NULL;
curr=curr->next;
if (p != NULL) p = p->next;
if (q != NULL) q = q->next;
}
if (carry > 0) {
curr->next = (struct ListNode*)malloc(sizeof(struct ListNode));
curr->next->val=carry ;
curr->next->next=NULL;
}
return dummyHead->next;//哇,这个竟然返回一个头结点的接下来所有的结点。好牛皮
}
我的解决方法之Java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode(0);
ListNode p = l1, q = l2, curr = dummyHead;
int carry = 0;
while (p != null || q != null) {
int x = (p != null) ? p.val : 0;
int y = (q != null) ? q.val : 0;
int sum = carry + x + y;
carry = sum / 10;
curr.next = new ListNode(sum % 10);
curr = curr.next;
if (p != null) p = p.next;
if (q != null) q = q.next;
}
if (carry > 0) {
curr.next = new ListNode(carry);
}
return dummyHead.next;
}
}
我的解决方法之Python
# Definition for singly-linked list.
# class ListNode(object): python中类 类中的函数 以及函数的参数的理解
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dummyHead=ListNode(0)# 注意Python中类的实例的初始化
curr=dummyHead
carry=0
while l1 or l2:
x = l1.val if l1.val else 0
y = l2.val if l2.val else 0
sum=x+y+carry
carry =sum/10
curr.next=ListNode(sum%10)
curr=curr.next
l1=l1.next
l2=l2.next
if carry>0:
curr.next=ListNode(carry)
curr=curr.next
return dummyHead.next
我的解决方法之Swift
/**
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init(_ val: Int) {
* self.val = val
* self.next = nil
* }
* }
*/
//‘??’ 运算符可以用于判断 变量/常量 的数值是否是 nil.不为 nil ,则取变量或者常量本身的值,如果是 nil 则使用后面的值替代
class Solution {
func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {//Optional是为了解决nil类型不详的问题
let dummyHead:ListNode? = ListNode(0)
var curr = dummyHead//由于curr是会发生变化的,所以在这里我们声明为变量
var carry=0
var x=0
var y=0
var sum=0
var p1 = l1//cannot assign to value: 'l1' is a 'let' constant
var p2 = l2//由于l1,l2是常量,而在接下来的程序中要用到,且会变化,因此复制一个变量出来
while p1 != nil || p2 != nil//这里之所以可以这样,把l1与类型不明确的nil比较是因为前面函数定义l1用了‘?’
{
x = p1.flatMap { $0.val } ?? 0
y = p2.flatMap { $0.val } ?? 0
sum = x + y + carry
carry = sum / 10
curr!.next = ListNode(sum % 10)//上面是?,不确定,这里要么是?(如果有值的话执行后面的)要么是!(一定有值,执行)
curr=curr!.next
p1=p1?.next
p2=p2?.next//这里如果是!会报错,unexpectedly found nil while unwrapping an Optional value
}
if carry > 0
{
curr!.next = ListNode(carry)
curr = curr!.next
}
return dummyHead!.next
}
}
—–由于Swift是自己刚刚接触,从零开始,所有的东西,都是自己一点一点的查看文档,百度自己搜使用方法的,而且是严格按照算法来编写的,不仅仅是Swift,其他几种语言也是严格按照之前的算法来编写的,我想这样能够更清楚的体现出语言之间的不同,从对比中来学习他们的差别。