// TwoNum.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <vector>
#include <map>
using namespace std;
//Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
vector<int> TwoSum(vector<int> nums, int target)
{
vector<int> res;
const int len = nums.size();
map<int, int> mp;
for (int i = 0; i < len;i++)
{
mp[nums[i]] = i;
}
map<int, int>::iterator it = mp.end();
for (int i = 0; i < len; i++)
{
it = mp.find(target - nums[i]);
if (mp.end() != it && i != it->second)
{
res.push_back(i+1);
res.push_back(it->second+1);
break;
}
}
return res;
}
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
{
ListNode nodeTemp(INT_MIN);
ListNode* pPre = &nodeTemp;
ListNode* la = l1;
ListNode* lb = l2;
ListNode* pListNew = pPre;
int flag = 0;
for (;
nullptr != la || nullptr != lb;
la = (nullptr == la) ? nullptr : la->next,
lb = (nullptr == lb) ? nullptr : lb->next,
pListNew = pListNew->next)
{
ListNode* pNewNode = nullptr;
const int a = (nullptr != la)? la->val : 0;
const int b = (nullptr != lb) ? lb->val : 0;
int value = (a + b + flag) % 10;
flag = (a + b + flag) / 10;
printf("value:%d flag:%d\n", value, flag);
pNewNode = new ListNode(value);
pListNew->next = pNewNode;
}
if (flag > 0)
{
pListNew->next = new ListNode(flag);
}
return pPre->next;
}
};
int main()
{
#if 0
vector<int> vec = { 3,2,4 };
Solution s;
vector<int> res = s.TwoSum(vec, 6);
for (auto item : res)
{
printf(" %d\n", item);
}
#endif // 0
ListNode a1(1);
ListNode a2(8);
//ListNode a3(4);
a1.next = &a2;
//a2.next = &a3;
ListNode b1(0);
//ListNode b2(22);
//ListNode b3(8);
//b1.next = &b2;
//b2.next = &b3;
ListNode* la = &a1;
ListNode* lb = &b1;
Solution s;
ListNode* pResult = s.addTwoNumbers(la, lb);
while (pResult)
{
ListNode* pDelNode = pResult;
printf("node: %d\n", pDelNode->val);
pResult = pResult->next;
delete pDelNode;
pDelNode = nullptr;
}
return 0;
}