#include <iostream>
#include <vector>
#include<algorithm>
#include <queue>
using namespace std;
/************************************************************************/
/*
Problem:
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
//其实就是 342+465 = 807
Author : crazys_popcorn@126.com
DateTime: 2017年8月7日 17:41:33
*/
/************************************************************************/
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
{
//双指针。指向同一个开始位置。用于返回
ListNode *List = new ListNode(0);
ListNode *head = List;
int jinwei = 0;
if (l1 == NULL && l2 == NULL)
return NULL;
while (l1||l2)
{
//把给个位数相加。 //第一轮进位为0.第二轮看看上一轮的进位是否大于10 大于10 就是1
int num =( l1 ? l1->val:0 )+ (l2 ? l2->val:0) + jinwei;
if (num >= 10)
{
num -= 10;
//大于10 进位 1
jinwei = 1;
}
else
jinwei = 0;
//当前为不修改。直接修改 next 一个元素。
List->next = new ListNode(num);
//把指针,移到下一位 //重复上面步骤。 修改下一位。
List = List->next;
if (l1)
l1 = l1->next;
if (l2)
l2 = l2->next;
}
if (jinwei)
{
//看看最后的哪一位。是不是进位了。
List->next = new ListNode(1);
}
return head->next;
}
};
void main()
{
ListNode *t1 = new ListNode(0);
ListNode *t2 = new ListNode(0);
ListNode *t3 = new ListNode(0);
t1->val = 2;
t2->val = 4;
t3->val = 3;
t1->next = t2;
t2->next = t3;
ListNode *t11 = new ListNode(0);
ListNode *t22 = new ListNode(0);
ListNode *t33 = new ListNode(0);
t11->val = 5;
t22->val = 6;
t33->val = 4;
t11->next = t22;
t22->next = t33;
Solution s1;
s1.addTwoNumbers(t1, t11);
system("pause");
return ;
}
LeetCode Add Two Numbers C++
最新推荐文章于 2022-10-28 16:16:58 发布