You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order , and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order , and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example 1:
Example 2:
Example 3:
Constraints:
算法思路
这道题目是一道比较基础的链表方面的题目, 解题思路就是建立一个新链表, 然后把输入的两个链表从头往后撸, 每两个相加, 添加一个新节点到新链表后面。
为了避免两个输入链表同时为空,我们建立一个
dummyHead
结点,将两个结点相加生成的新结点按顺序加到dummyHead
结点之后,由于dummyHead
结点本身不能变,所以我们用一个指针cur
来指向新链表的最后一个结点。可以开始让两个链表相加了,这道题好就好在最低位在链表的开头,所以我们可以在遍历链表的同时按从低到高的顺序直接相加。
while
循环的条件两个链表中只要有一个不为空就行,由于链表可能为空,所以我们在取当前结点值的时候,先判断一下,若为空则取 0,否则取结点值。然后把两个结点值相加,同时还要加上进位 carry。然后更新
carry
,直接sum/10
即可,然后以sum % 10
为值建立一个新结点,连到cur
后面,然后cur
移动到下一个结点。之后再更新两个结点,若存在,则指向下一个位置。while 循环退出之后,最高位的进位问题要最后特殊处理一下,若 carry 为 1,则再建一个值为 1 的结点,代码如下:复杂度分析
The text was updated successfully, but these errors were encountered: