温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Add Two Numbers

发布时间:2020-07-01 22:40:10 来源:网络 阅读:424 作者:程红玲OOO 栏目:编程语言

描述

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


分析:342+465=807——>708


Add.h

#pragma once
#include <iostream>

using namespace std;

typedef struct ListNode{
	int _var;
	ListNode *_next;

	ListNode(int var)
		:_var(var)
		, _next(NULL)
	{}
}node, *node_p;

class Solution
{
public:
	node_p add_two_number(ListNode *l1, ListNode *l2)
	{
		node_p NewHead = NULL;
		node_p pa = l1->_next;
		node_p pb = l2->_next;
		int mod = 0;
		while (pa != NULL || pb != NULL){
		    int a = 0;
		    int b = 0;
			if (pa != NULL)
				a = pa->_var;
			if (pb != NULL)
				b = pb->_var;
			
			int ret = (a + b + mod) % 10;
			mod = (a + b + mod) / 10;
			node_p tmp = new node(ret);
			tmp->_next = NewHead;
			NewHead = tmp;

			if (pa != NULL)
				pa = pa->_next;
			if (pb != NULL)
				pb = pb->_next;
		}
		if (mod > 0){
			node_p tmp = new node(mod);
			tmp->_next = NewHead;
			NewHead = tmp;
		}

		return NewHead;
	}
};

Add.cpp

#include "Add_List.h"
#include  <stdlib.h>
using namespace std;


int main()
{
	Solution s1;
	node_p l1 = new node(-1);
	node_p pa = l1;
	pa->_next = new node(4);
	pa = pa->_next;
	pa->_next = new node(6);
	pa = pa->_next;
	pa->_next = new node(7);
	pa = pa->_next;
	pa->_next = new node(8);
	
	node_p l2 = new node(-1);
	node_p pb = l2;
	pb->_next = new node(1);
	pb = pb->_next;
	pb->_next = new node(2);
	pb = pb->_next;
	pb->_next = new node(5);
	pb = pb->_next;
	pb->_next = new node(6);
	pb = pb->_next;
	pb->_next = new node(3);

	node_p ret=s1.add_two_number(l1,l2);

	system("pause");
	return 0;
}

调试查看结果:

Add Two Numbers


// LeetCode, Add Two Numbers

// 时间复杂度 O(m+n),空间复杂度 O(1)

class Solution{
public:
	ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
		ListNode dummy(-1); // 头节点
		int carry = 0;
		ListNode *prev = &dummy;
		for (ListNode *pa = l1, *pb = l2;
			pa != nullptr || pb != nullptr;
			pa = pa == nullptr ? nullptr : pa->next,
			pb = pb == nullptr ? nullptr : pb->next,
			prev = prev->next) {
			const int ai = pa == nullptr ? 0 : pa->val;
			const int bi = pb == nullptr ? 0 : pb->val;
			const int value = (ai + bi + carry) % 10;
			carry = (ai + bi + carry) / 10;
			prev->next = new ListNode(value); // 尾插法
		}
		if (carry > 0)
			prev->next = new ListNode(carry);
		return dummy.next;
	}
};


《完》


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI