【LeetCode】2. Add Two Numbers
生活随笔
收集整理的這篇文章主要介紹了
【LeetCode】2. Add Two Numbers
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
傳送門:https://leetcode.com/problems/add-two-numbers/
一、題目描述
You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
二、示例
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
三、分析
涉及鏈表的知識,從左到右遍歷鏈表,依次相加,每一個位置生成一個新的結點即可。
考慮邊界條件:
- 進位的的處理:carry表示進位,當最后一位還有進位時,即使 l1 和 l2 均為NULL的情況下,還需要生成一個新的結點,所以while的條件中加入了 carry != 0 判斷項。
- 返回頭結點:當頭結點為NULL的時候記錄頭結點,并且讓p等于頭結點;后續情況讓 p->next 等于新的結點,并讓 p 指向 p->next。
四、實現
/*** Definition for 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) {ListNode *head = NULL,*p;int carry = 0, sum = 0;while(l1 != NULL || l2 != NULL || carry != 0){sum = 0;if(l1 != NULL){sum = sum + l1->val;l1 = l1->next;}if(l2 != NULL){sum = sum + l2->val;l2 = l2->next;}sum = sum + carry;carry = sum / 10;sum = sum % 10;ListNode *newNode = new ListNode(sum);if(head == NULL){head = newNode;p = newNode;}else{p->next = newNode;p = p->next;}}return head;} };總結
以上是生活随笔為你收集整理的【LeetCode】2. Add Two Numbers的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【LeetCode】1. Two Sum
- 下一篇: 【编程1】 Two Sum + 哈希算法