Example:
You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
答案:
//饶了很多弯路,最后发现自己没有注重条件的组合,导致有非常多的条件判断。。。还需更努力啊
#include "stdafx.h"
#include <iostream>
#include <unordered_map>
using namespace std;
struct ListNode{
int val;
ListNode* next;
ListNode(int x = 0) : val(x), next(NULL){
}
};
class Solution{
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2){
// if(l1 && l2){
// ListNode* pRes = new ListNode(0);
// ListNode* pHeader = pRes;
//
// int sum = 0;
//
// while(l1 || l2){
// sum /= 10;
//
// if(l1){
// sum += l1->val;
// l1 = l1->next;
// }
// if(l2){
// sum += l2->val;
// l2 = l2->next;
// }
//
// pRes->next = new ListNode(sum % 10);
// pRes = pRes->next;
// }
// //两项之和大于10,为结果在添加一项
// if(sum / 10 == 1){
// pRes->next = new ListNode(1);
// }
//
// return pHeader->next;
// }
// return NULL;
//大牛做法。。。。
ListNode preHead(0), *p = &preHead;
int extra = 0; //进位
while (l1 || l2 || extra) {
int sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + extra; //两元素之和
extra = sum / 10;
p->next = new ListNode(sum % 10); //取其模作为该值
p = p->next;
l1 = l1 ? l1->next : l1;
l2 = l2 ? l2->next : l2;
}
return preHead.next;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
// ListNode* pLeft = new ListNode(2);
// ListNode* pLeftHeader = pLeft;
// pLeft->next = new ListNode(4);
// pLeft = pLeft->next;
// pLeft->next = new ListNode(3);
//
// ListNode* pRight = new ListNode(5);
// ListNode* pRightHeader = pRight;
// pRight->next = new ListNode(6);
// pRight = pRight->next;
// pRight->next = new ListNode(4);
// ListNode* pLeft = new ListNode(5);
// ListNode* pLeftHeader = pLeft;
//
// ListNode* pRight = new ListNode(5);
// ListNode* pRightHeader = pRight;
// ListNode* pLeft = new ListNode(9);
// ListNode* pLeftHeader = pLeft;
//
// ListNode* pRight = new ListNode(9);
// ListNode* pRightHeader = pRight;
//ListNode* pLeft = new ListNode(9);
//ListNode* pLeftHeader = pLeft;
//pLeft->next = new ListNode(8);
//ListNode* pRight = new ListNode(1);
//ListNode* pRightHeader = pRight;
ListNode* pLeft = new ListNode(1);
ListNode* pLeftHeader = pLeft;
ListNode* pRight = new ListNode(9);
ListNode* pRightHeader = pRight;
pRight->next = new ListNode(9);
Solution slt;
ListNode* pRes = slt.addTwoNumbers(pLeftHeader, pRightHeader);
while(pRes){
std::cout << pRes->val << " ";
ListNode* tmp = pRes->next;
delete pRes;
pRes = tmp;
}
while(pLeftHeader){
ListNode* tmp = pLeftHeader->next;
delete pLeftHeader;
pLeftHeader = tmp;
}
while(pRightHeader){
ListNode* tmp = pRightHeader->next;
delete pRightHeader;
pRightHeader = tmp;
}
std::cout << "\n";
return 0;
}