1. 题目
2.解题思路
找到长度长的链表,把短链表的值直接加到长链表对应的值上,之后判断长链表的值是否大于9,大于则进位,如果后一位为空,得添加一个节点
3.代码实现
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head1 = l1;
ListNode head2 = l2;
ListNode first = new ListNode(0);
int count1 = 0, count2 = 0;
while(head1 != null) {
count1++;
head1 = head1.next;
}
while(head2 != null) {
count2++;
head2 = head2.next;
}
if(count1 > count2) {
head1 = l1;
first = l1;
head2 = l2;
}else {
head1 = l2;
first = l2;
head2 = l1;
}
ListNode head = first;
while(head2 != null) {
head1.val += head2.val;
head1 = head1.next;
head2 = head2.next;
}
while(first != null) {
if(first.val > 9) {
int shi = first.val / 10;
first.val %= 10;
if(first.next == null) {
ListNode next = new ListNode(shi);
first.next = next;
}else {
first.next.val += shi;
}
}
first = first.next;
}
return head;
}
}
4.解法拓展
再建一个链表,将两个链表的值相加,短链表结束之后,将短链表的值设为0,长链表每次加短链表的值就是长链表的值,设置carry,进位了carry=1,没进位=0
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) ? p.val : 0;
int y = (q != null) ? q.val : 0;
int sum = carry + x + y;
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 > 0) {
curr.next = new ListNode(carry);
}
return dummyHead.next;
}
作者:LeetCode
链接:https://leetcode-cn.com/problems/add-two-numbers/solution/liang-shu-xiang-jia-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。