【LeetCode】137链表求和
题目:
解题思路:
对两个链表从头到尾遍历,将每个位的数字相加并插入到新建链表上。注意处理两个链表不等长。
https://leetcode-cn.com/problems/sum-lists-lcci/solution/javaji-bai-100-bi-kan-by-wonderzlf-v7dm/
代码:
public class LC145 { public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
// 判空输入
if (l1==null) {
return l2;
} else if (l2==null) {
return l1;
}
// 遍历两个输入链表
ListNode head = null;
ListNode first = null;
int tmp = 0;
while (l1!=null ||l2!=null) {
tmp =tmp+(l1!=null?l1.val:0)+(l2!=null?l2.val:0);
if (first==null) {
first = new ListNode(tmp%10);
head = first;
} else {
first.next = new ListNode(tmp%10);
first = first.next;
}
l1=(l1!=null?l1.next:null);
l2=(l2!=null?l2.next:null);
tmp /= 10;
}
// 处理相加的进位
if (tmp!=0) {
first.next = new ListNode(tmp);
}
return head;
}
}
以上是 【LeetCode】137链表求和 的全部内容, 来源链接: utcz.com/z/509487.html