当前位置: 面试刷题>> 链表求和Ⅰ (经典算法题500道)
### 题目描述补充
**链表求和Ⅰ**
给定两个非空链表,表示两个非负整数。数字按逆序方式存储在链表中,每个节点包含一个数字。将这两个数相加,并以相同的方式(即逆序)返回一个新的链表。
你可以假设除了数字0之外,这两个数字都不会以0开头。
**示例**:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
### PHP 示例代码
```php
class ListNode {
public $val = 0;
public $next = null;
function __construct($val = 0, $next = null) {
$this->val = $val;
$this->next = $next;
}
}
function addTwoNumbers($l1, $l2) {
$dummy = new ListNode(0); // 创建一个哑节点,方便操作
$current = $dummy;
$carry = 0; // 进位
while ($l1 !== null || $l2 !== null || $carry > 0) {
$x = ($l1 !== null) ? $l1->val : 0;
$y = ($l2 !== null) ? $l2->val : 0;
$sum = $x + $y + $carry;
$carry = intdiv($sum, 10); // 获取进位
$current->next = new ListNode($sum % 10); // 当前位的值
$current = $current->next;
if ($l1 !== null) {
$l1 = $l1->next;
}
if ($l2 !== null) {
$l2 = $l2->next;
}
}
return $dummy->next; // 跳过哑节点,返回结果链表的头节点
}
```
### Python 示例代码
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def addTwoNumbers(l1, l2):
dummy = ListNode(0)
current = dummy
carry = 0
while l1 or l2 or carry:
x = l1.val if l1 else 0
y = l2.val if l2 else 0
sum = carry + x + y
carry = sum // 10
current.next = ListNode(sum % 10)
current = current.next
if l1:
l1 = l1.next
if l2:
l2 = l2.next
return dummy.next
```
### JavaScript 示例代码
```javascript
function ListNode(val, next) {
this.val = (val===undefined ? 0 : val)
this.next = (next===undefined ? null : next)
}
function addTwoNumbers(l1, l2) {
let dummy = new ListNode(0);
let current = dummy;
let carry = 0;
while (l1 !== null || l2 !== null || carry > 0) {
let x = (l1 !== null) ? l1.val : 0;
let y = (l2 !== null) ? l2.val : 0;
let sum = carry + x + y;
carry = Math.floor(sum / 10);
current.next = new ListNode(sum % 10);
current = current.next;
if (l1 !== null) {
l1 = l1.next;
}
if (l2 !== null) {
l2 = l2.next;
}
}
return dummy.next;
}
```
**码小课网站中有更多相关内容分享给大家学习**,包括算法进阶、数据结构深入等,希望大家都能成为算法高手!