当前位置:网站首页>剑指 Offer II 025. 链表中的两数相加
剑指 Offer II 025. 链表中的两数相加
2022-06-25 12:19:00 【小白码上飞】
一句话概要
先反转链表,然后在从头开始加和进位。
题目
给定两个 非空链表 l1和 l2 来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。
可以假设除了数字 0 之外,这两个数字都不会以零开头。

链接:https://leetcode.cn/problems/lMSNwu
思路
其实就是两个数字做加法。但是正常计算都是从右往左加和、进位,但是用链表表示一个数字,就只能从左往右去计算数字。所以先反转两个链表,然后一起移动加和,就可以了。
解法:先反转链表,再加和
代码
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
l1 = reverseList(l1);
l2 = reverseList(l2);
ListNode next = null;
int add = 0;
while (l1 != null || l2 != null) {
int sum = add;
if (l1 != null) {
sum += l1.val;
l1 = l1.next;
}
if (l2 != null) {
sum += l2.val;
l2 = l2.next;
}
add = sum / 10;
ListNode current = new ListNode(sum % 10);
current.next = next;
next = current;
}
if (add != 0) {
ListNode current = new ListNode(add);
current.next = next;
return current;
}
return next;
}
public ListNode reverseList(ListNode head) {
ListNode current = head;
ListNode pre = null;
ListNode next;
while (current != null) {
next = current.next;
current.next = pre;
pre = current;
current = next;
}
return pre;
}
边栏推荐
- Jenkins Pipeline使用
- Command line garbled
- CUDA error: unspecified launch failure
- GNSS receiver technology and application review
- 2021-09-02
- Laravel multi project mutual access
- 初识CANOpen
- Penetration tool environment - installing sqli labs in centos7 environment
- Figure explanation of fiborache sequence
- Qt5 multi thread operation implemented by object base class and use of movetothread method
猜你喜欢
随机推荐
Oracle trigger error report table or view does not exist
[data visualization] 360 ° teaching you how to comprehensively learn visualization - Part 1
MySQL adds, modifies, and deletes table fields, field data types, and lengths (with various actual case statements)
1024水文
High performance + million level Excel data import and export
list. replace, str.append
Event triggered when El select Clear clears content
First acquaintance with CANopen
Foreach method of array in JS
更新pip&下载jupyter lab
Micro engine generates QR code
QT TCP UDP network communication < theory >
Matlab simulation of m-sequence
Wechat forbids sharing
Talk about 11 key techniques of high availability
2021-09-28
Elemntui's select+tree implements the search function
Total number of MySQL statistics, used and unused
Common colors for drawing
Meichuang was selected into the list of "2022 CCIA top 50 Chinese network security competitiveness"









