Add Two Numbers
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
分析: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; }
调试查看结果:
// 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; } };
《完》
本文出自 “零蛋蛋” 博客,请务必保留此出处http://lingdandan.blog.51cto.com/10697032/1774139
以上是关于Add Two Numbers的主要内容,如果未能解决你的问题,请参考以下文章