hot 100 meddium
1. 第二题 两数字相加
见原题:https://leetcode-cn.com/problems/add-two-numbers/
链表中个位置上数字相加,满10进位,最高位不是0

解题思路:
java链表,取余,商,进位
-
新建类ListNode,保存value和下一个节点
class ListNode { int val; ListNode next; public ListNode() { } public ListNode(int val) { this.val = val; } public ListNode(int val, ListNode next) { this.val = val; this.next = next; } }
-
while循环解题
思路:- 找到当前节点应该存的值:低位进值+L1节点对应值+L2节点对应值 除10取商
- 当前值如果超过了9,需要进位0或者1
需要的变量:低位 low 高位high 当前节点两个节点所在值的和 两个空对象ListNode,一个往后移动,一个保持头部位置不变
int low = 0; int high = 0; ListNode res = new ListNode(); ListNode p = res; int sum = 0; while (l1 != null || l2 != null) { if (l1 == null) { sum = l2.val + high; } else if (l2 == null) { sum = l1.val + high; } else { sum = l1.val + l2.val + high; } low = sum % 10; high = sum / 10; p.next = new ListNode(low); //新建节点,并把尾指针后移 p = p.next; if (l1!=null ) { l1 = l1.next; } if (l2!=null) { l2 = l2.next; } }
- 题目的坑
如果最高位只有一个high不为0,已经跳出循环了,这时候该怎么处理呢?新建节点追加到末尾
if (high != 0) { p.next = new ListNode(high); }
难度系数:三颗星
网友评论