python
1.考察的是对链表的操作;
2.python中深拷贝与浅拷贝。
# 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:
head = curr = ListNode()
# head用来返回,curr用来遍历,head与curr是浅拷贝,头节点可以只包括指针
carry = val = 0
while carry or l1 or l2:
val = carry
if l1: l1, val = l1.next, l1.val + val
if l2: l2, val = l2.next, l2.val + val
carry, val = divmod(val, 10) # divmod()输出一个tuple,包括商和余数
curr.next = ListNode(val)
curr = curr.next # 遍历到新加元素上
return head.next
C++
/**
* 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) {
// num1表示节点和的个位,nums2表示节点和的十位
// 因为题目的链表已经都是个位开头,所以能对齐,直接模拟加法过程
// 注意如果最后还有进位没用补,需要额外节点补上
ListNode* dummy = new ListNode(-1);
ListNode* pre = dummy;
int num1 = 0, num2 = 0;
int l1_val = 0, l2_val = 0;
while (l1 || l2) {
int l1_val = 0, l2_val = 0;
if (l1) {
l1_val = l1->val;
l1 = l1->next;
}
if (l2) {
l2_val = l2->val;
l2 = l2->next;
}
num1 = l1_val + l2_val + num2;
num2 = num1 / 10;
num1 %= 10;
ListNode* newnode = new ListNode(num1);
pre->next = newnode;
pre = pre->next;
}
if (num2 != 0) {
ListNode* extra = new ListNode(num2);
pre->next = extra;
}
return dummy->next;
}
};