结构体访问成员变量时用.
,例如head.val
指针访问成员变量时用->
,例如current->val
写链表时,应使用 new 的初始化方法:ListNode* head = new ListNode();
空指针nullptr
可以用if(pointer)
判断
这道题思路比较简单,可以用一个变量sum
解决进位问题,空间复杂度O(1).
/**
* 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();
ListNode* current = head;
int sum = 0;
bool flag = true;
while(l1 || l2 || sum){
if(l1) {
sum += l1->val;
l1 = l1->next;
}
if (l2){
sum += l2->val;
l2 = l2->next;
}
if(flag) {
current->val = sum % 10;
flag = false;
}
else {
current->next = new ListNode(sum%10);
current = current->next;
}
sum /= 10;
}
return head;
}
};