您的位置:首页 > 理论基础 > 数据结构算法

2. Add Two Numbers

2016-06-30 07:55 369 查看
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

Subscribe to see which
companies asked this question

//大概意思就是给定两个单链表,对两个链表按顺序求对应每两个结点值的和,并将结果放倒一个新的链表里,但并不是简单的相加,还有一定规则
//规则:
//先设置一个状态值为0,先对两个对应的结点的值求和,再将状态值与两个结点值的和相加,
//1.若相加后的结果大于9,将值减去10,将相减后的结果取代状态值与两个结点值相加后的结果,
//并放入到新的链表里,状态值设置为1,参与下两个结点的求和
//2.若相加后的结果不大于9,直接将结果放倒新的链表里,状态值为0不变,继续下两个结点的求和
//每求和一次,存放结果的链表都新建一个结点,利用定义的构造将结果放入到新的结点里,所有运算结束后得到的是一个新链表
#include "stdafx.h"
#include<list>
//define the 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)
{
int state = 0;
ListNode temp(0);
ListNode* p = &temp;
while (l1||l2)
{
int result = state;
if (l1)
{
result += l1->val;
l1 = l1->next;
}
if (l2)
{
result += l2->val;
l2 = l2->next;
}
if (result > 9)
{
result -= 10;
state = 1;
}
else state = 0;
p->next = new ListNode(result);
p = p->next;
}
if (state)p->next = new ListNode(1);
return temp.next;
}
};

//main函数在VS中编译要写,在leetcode上提交不需要写
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息