C++
链表通过指针相连起来,只要有头指针指向第一个节点就可以找到整个的链表,然后链表的创建和查找需要定义一个额外的节点指针,用来不断的指向next指针指向的内存空间
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* head = new ListNode(-1);
ListNode* h = head; //移动指针
int sum = 0; //每一位的加和
int carry = 0; //进位标志
while(l1!=nullptr||l2!=nullptr||carry){
sum = carry; //每次循环就是运算不同位的加和,每次开始前都要重新赋carry非0即1
//这样也包含了最后一位进一的情况
if(l1!=nullptr){
sum+=l1->val;
l1 = l1->next;//移动l1指针
}
if(l2!=nullptr){
sum+=l2->val;
l2 = l2->next;
}
carry=sum>=10?1:0;
h->next = new ListNode(sum%10);
h = h->next;
}
return head->next; //返回第二个节点后的链表
}
};
Python
法一(思路同上):
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
head = h = ListNode(-1)
sum = 0
carry = False
while l1 or l2:
sum = 0
if l1:
sum += l1.val
l1 = l1.next
if l2:
sum += l2.val
l2 = l2.next
if carry:
sum+=1
carry = 1 if sum>=10 else 0
h.next = ListNode(sum%10)
h = h.next
if carry: h.next = ListNode(1)
return head.next
法二(思路一样,就是更简洁):
divmod(a, b)函数返回a/b的取整和a%b
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
current = dummy = ListNode()
carry, value = 0, 0
while carry or l1 or l2:
value = carry
if l1: l1, value = l1.next, l1.val + value
if l2: l2, value = l2.next, l2.val + value
carry, value = divmod(value, 10)
current.next = ListNode(value)
current = current.next
return dummy.next