leetcode-2 Add Two Numbers
思路:
1. 定义两个游标迭代器,分别初始化为指向链表头部l1,l2;
2. 从头部开始扫描l1和l2,两个游标指示元素相加之和取个位与进位相加,得到的值作为当前位的结果保存,并根据实际情况进行进位操作,如果某个游标先结束,则该游标及其后继都被标记为NULL;
3. 判断最后一位是否有进位,如果有,把最后一个进位最为最高位保存下来;
4. 返回最终链表的真实头指针(代码中加入了一个空的头结点,是为了便于代码迭代步骤的统一性);
源码如下:
/**
* 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* cursor1 = l1;
ListNode* cursor2 = l2;
ListNode* cursor3 = new ListNode(0);
ListNode* l3 = cursor3;
ListNode* temp = NULL;
int val1=0,val2 = 0;
bool incre = false;
int lowAdd = 0;
while (cursor1 != NULL || cursor2 != NULL) {
val1 = cursor1!=NULL?cursor1->val : 0;
val2 = cursor2!=NULL?cursor2->val :0;
temp = new ListNode(0);
temp->val = val1 + val2 + lowAdd;
temp->val <10 && (incre = false);
temp->val >= 10 && (temp->val -= 10, incre = true);
cursor3->next = temp;
cursor3 = temp;
temp = NULL;
lowAdd = incre ? 1 : 0;
cursor1 = cursor1!=NULL? cursor1->next : NULL;
cursor2 = cursor2!=NULL? cursor2->next : NULL;
}
incre && (cursor3->next = new ListNode(lowAdd));
cursor3= NULL;
l3 = l3->next;
delete cursor3;
//reverseNodes(l1);
return l3;
}
void reverseNodes(ListNode* &l) {
ListNode* cursor = l;
ListNode* temp = NULL;
l = NULL;
while (cursor != NULL) {
temp = cursor->next;
cursor->next = l;
l = cursor;
cursor = temp;
}
}
};