Linked List Math
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.
| 相似题目: | |
|---|---|
| 简单 | - Add Binary - Sum of Two Integers - Add Strings |
| 中等 | - Multiply Strings - Add Two Numbers II - Add to Array-Form of Integer |
初等数学
伪代码如下:
- 将当前节点初始化为返回链表的哑节点 (统一节点插入操作)
- 将进位
carry初始化为0 - 将
p和q分别初始化为链表l1和l2的头部 - 遍历链表
l1和l2直至到达它们的尾端。- 将x设置为节点p的值。如果p已经到达
l1的末尾,则将其值设置为0。 - 将y设置为节点q的值。如过q已经到达
l2的末尾,则将其值设置为0。 - 设定 sum = x + y + carry
- 更新进位的数值为,carry = sum / 10
- 创建一个数值为(sum mod 10)的新节点,并将其设置为当前节点的下一个节点,再将当前节点指向新创建的节点
- 同时,将p和q 前进到下一个节点
- 将x设置为节点p的值。如果p已经到达
- 检查carry是否等于1,若是,向链表尾追加一个值为1的新结点
- 返回哑节点的下一个节点
:::info 一个循环就解决了,刚开始做的时候用了3个循环,还没有解决!!!
- 若指向空,则赋值为0 很妙
- curr 和 哑节点 都非常重要
- 一个循环的话,要注意什么时候索引不能前进 :::
/*** 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 dummyHead = new ListNode(0);ListNode p = l1, q = l2, curr = dummyHead;int carry = 0;while (p != null || q != null) {int x = (p == null) ? 0 : p.val;int y = (q == null) ? 0 : q.val;int sum = x + y + carry;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 == 1) {curr.next = new ListNode(1);}return dummyHead.next;}}
