标签:
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
思路:
1、最开始看错题了,还自己写了一个reverse linked list
2、题目是说原数字是倒过来存储的,所以上面的示例Input是 342 + 465,答案是807,Output也是倒过来存放的
3、也就是说题目已经把数字从个位对齐了,得到的Ouput也是不需要再倒序的,只需要挨着加上去就行
4、主要的伪代码为 iNewNum = iNumber1 + iNumber2 + iCarryFlags
5、每次如果iNewNum大于等于10,那么iCarryFlag设置为1,iNewNum减小10,否则设置为0
6、注意边界情况,也就是第一个linked list和第二个linked list都加完了,但这个时候iCarryFlag不为0,说明还要向上进一位
7、所以循环条件为 while (第一个链表当前节点不为NULL || 第二个链表当前节点不为NULL || iCarryFlag);
源代码如下:
#include <iostream> #include <string> #include <vector> #include <unordered_map> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { if (l1 == NULL && l2) return l2; if (l2 == NULL && l1) return l1; ListNode * pCur1 = l1; ListNode * pCur2 = l2; ListNode * pResult = NULL; ListNode * pResultTail = NULL; ListNode * pNew = NULL; int iCarryFlag = 0; while (pCur1 || pCur2 || iCarryFlag) { pNew = new ListNode(0); if (pCur1 && pCur2) { pNew->val = pCur1->val + pCur2->val + iCarryFlag; } else if (pCur1) { pNew->val = pCur1->val + iCarryFlag; } else if (pCur2) { pNew->val = pCur2->val + iCarryFlag; } else { pNew->val = iCarryFlag; } iCarryFlag = 0; if (pNew->val >= 10) { pNew->val = pNew->val - 10; iCarryFlag = 1; } pNew->next = NULL; if (pResult == NULL) { pResult = pNew; pResultTail = pNew; } else { pResultTail->next = pNew; pResultTail = pNew; } if (pCur1) pCur1 = pCur1->next; if (pCur2) pCur2 = pCur2->next; } return pResult; } }; int main() { system("pause"); return 0; }
leetcode [002] : Add Two Numbers
标签:
原文地址:http://www.cnblogs.com/lqy1990cb/p/4799068.html