两数相加
Add Tow Numbers
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:
1 | Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) |
题目大意
2 个非空的逆序链表, 低位开始相加, 结果也以逆序输出.
解题思路
两数相加主要需要处理 进位
的问题.
1 | Input: (9 -> 9) + (1 -> ) |
定义好如下链表结构:
1 | type ListNode struct { |
初始化一个空链表用于存储结果, 同时赋值给游标, 按位循环相加, 并处理进位, 结束条件不能使用 l.Next != nil, 这样还要额外去处理进位问题, 直接使用 l != nil 进行结束判断.
代码
1 | func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { |