【LeetCode 2】两数相加(链表)
給你兩個(gè)?非空 的鏈表,表示兩個(gè)非負(fù)的整數(shù)。它們每位數(shù)字都是按照?逆序?的方式存儲(chǔ)的,并且每個(gè)節(jié)點(diǎn)只能存儲(chǔ)?一位?數(shù)字。
請你將兩個(gè)數(shù)相加,并以相同形式返回一個(gè)表示和的鏈表。
你可以假設(shè)除了數(shù)字 0 之外,這兩個(gè)數(shù)都不會(huì)以 0?開頭。
示例 1:
輸入:l1 = [2,4,3], l2 = [5,6,4]
輸出:[7,0,8]
解釋:342 + 465 = 807.
示例 2:
輸入:l1 = [0], l2 = [0]
輸出:[0]
示例 3:
輸入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
輸出:[8,9,9,9,0,0,0,1]
?
提示:
每個(gè)鏈表中的節(jié)點(diǎn)數(shù)在范圍 [1, 100] 內(nèi)
0 <= Node.val <= 9
題目數(shù)據(jù)保證列表表示的數(shù)字不含前導(dǎo)零
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/add-two-numbers
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請注明出處。
AC代碼:
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode() : val(0), next(nullptr) {}* ListNode(int x) : val(x), next(nullptr) {}* ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/ class Solution { public:ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {int c = 0;ListNode* head = new ListNode();ListNode* p = head;ListNode* q;while(l1 != nullptr && l2 != nullptr) {int s = l1->val + l2->val + c;c = s / 10;q = new ListNode(s%10);p->next = q;p = q;l1 = l1->next;l2 = l2->next;}while(l1 != nullptr) {int s = l1->val + c;c = s/10;q = new ListNode(s%10);p->next = q;p = q;l1 = l1->next;}while(l2 != nullptr) {int s = l2->val + c;c = s/10;q = new ListNode(s%10);p->next = q;p = q; l2 = l2->next; }if(c > 0) {q = new ListNode(c);p->next = q;}return head->next;} }; 創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的【LeetCode 2】两数相加(链表)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 国产CPU第一股!龙芯中科上市:开盘涨超
- 下一篇: Mr. Kitayuta‘s Techn