您好,登錄后才能下訂單哦!
描述
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; }
調(diào)試查看結(jié)果:
// LeetCode, Add Two Numbers
// 時間復(fù)雜度 O(m+n),空間復(fù)雜度 O(1)
class Solution{ public: ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { ListNode dummy(-1); // 頭節(jié)點(diǎn) 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; } };
《完》
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。