标签:numbers 定义 pre 遍历 节点 img problem flag ini
leetcode - 2:https://leetcode-cn.com/problems/add-two-numbers/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *ans = new ListNode(0); // 定义ListNode节点
ListNode *tip = ans; // 标记ans链表起始点,作为答案范围
int flag = 0; // 统计进位
while(l1 != NULL && l2 != NULL){ // l1和l2链表都没遍历完
flag += l1->val + l2->val;
ans->next = new ListNode(flag % 10);
ans = ans->next;
flag = flag/10;
l1 = l1->next;
l2 = l2->next;
}
while(l1 != NULL){ // l1链表都没遍历完
flag += l1->val;
ans->next = new ListNode(flag % 10);
ans = ans->next;
flag = flag/10;
l1 = l1->next;
}
while(l2 != NULL){ // l2链表都没遍历完
flag += l2->val;
ans->next = new ListNode(flag % 10);
ans = ans->next;
flag = flag/10;
l2 = l2->next;
}
while(flag){ // 还有进位未处理
ans->next = new ListNode(flag % 10);
ans = ans->next;
flag = flag/10;
}
return tip->next;
}
};
标签:numbers 定义 pre 遍历 节点 img problem flag ini
原文地址:https://www.cnblogs.com/baboon/p/12985109.html