题目描述
题目链接:https://leetcode.cn/problems/add-two-numbers/
思路
我首先想到了反转链表,但是实际没用上。
分析这道题难点在于进位怎么处理,不相等的链表如何处理,最后一位进位怎么处理。
- 创建一条空链表,进位标识符
jinwei
= 0; - 遍历两条链表,计算值相加,如果该节点为空则为0,再加上jinwei,得到sum;
- 存sum到新链表的节点,如果是头节点(head == null),那么新建两个指针指向头节点,存储值为sum%10;如果非头节点(head != null),新建下一节点存入值,往后移一位;
- 如果最后一个节点仍有进位信息,那么循环结束后还需要新增节点,存入jinwei值。
代码
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode l = null, head = null;
int jinwei = 0;
while(l1 != null || l2 != null){
int n1 = l1 != null ? l1.val : 0;
int n2 = l2 != null ? l2.val : 0;
int sum = n1 + n2 + jinwei;
if(head == null){
l = head = new ListNode(sum%10);
}else{
head.next = new ListNode(sum%10);
head = head.next;
}
jinwei = sum/10; //进位信息
if(l1 != null){
l1 = l1.next;
}
if(l2 != null){
l2 = l2.next;
}
}
if(jinwei > 0){
head.next = new ListNode(jinwei);
}
return l;
}
}