167.Add Two Numbers
1.Description(Easy)
You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored inreverse
order, such that the 1's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.
Example
Given7->1->6 + 5->9->2
. That is,617 + 295
.
Return2->1->9
. That is912
.
Given3->1->5
and5->9->2
, return8->0->8
.
Cracking The Coding Interview Linked List High Precision
2.Code
从l1, l2头节点开始,对应位置相加并建立新节点。用一个变量carry记录进位。注意几种特殊情况:
1.一个链表为空
l1: NULL
l2: 1->2
sum: 1->2
2.l1, l2长度不同,且结果有可能长度超过l1, l2中的最大长度
l1: 2->2
l2: 9->9->9
sum: 1->2->0->1
Last updated