2. Add Two Numbers

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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值