一、题目表述
给定两个代表非负数的链表,数字在链表中是反向存储的(链表头结点处的数字是个位数,第二个结点上的数字是十位数…),求这个两个数的和,结果也用链表表示。
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出: 7 -> 0 -> 8
You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
二、思路分析
- 本题考查基本的链表操作(链表遍历)
- 个位数加法特征,两个个位数相加最大是18,也就是对应位相加时最多产生进位1。
- 最后进位问题最后一个进位需要添加节点。
三、参考代码
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode l3 = null;
ListNode l11 = l1;
ListNode l22 = l2;
while(true){
if(l11 == null){
l3 = l2;
break;
}
if(l22 == null){
l3 = l1;
break;
}
int sum = l11.val + l22.val;
l11.val = sum;
l22.val = sum;
l11 = l11.next;
l22 = l22.next;
}
ListNode l33 = l3;
int carry = 0;
while(true){
l33.val += carry;
if(l33.val > 9){
l33.val -= 10;
carry = 1;
}else{
carry = 0;
}
if(l33.next == null){
if(carry == 1){
ListNode head = new ListNode(1);
l33.next = head;
}
break;
}else{
l33 = l33.next;
}
}
return l3;
}
}
四、测试连接
牛客网
力扣
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)