闲话链表(一) leetcode 之 Add Two Numbers
2014-10-12 20:32
375 查看
描述:
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
两个数各由一个单链表表示,低位在表头、高位在表尾,求两数相加结果,也用单链表表示。
原题出处:https://oj.leetcode.com/problems/add-two-numbers/
大家可以自己写代码提交,验证正确性
分析:这道题的求解方法很直观。一个大循环,循环内部两个指针指向的内容与低位的进位相加,保留余数,继续进位。关键要处理的地方是两点。
1、 何时结束整个循环?
一开始陷入了惯性思维,当有一个链表为空之后,认为只要把剩下的链表直接加在已经求得的结果之后即可。这种想法是完全错了的,链表L1为空后,它还可能有进位,进位与L2还需要做加法操作,这可能又会产生新的进位。所以循环的结束条件应该是
L1不为空|| L2不为空
2、 循环结束后是否要做些什么?
循环结束后并不一定完事大吉,这时候还可能有进位等着加向最高位呢。但这时候L1 L2已经为空,我们必须新生成一个节点单独存储进位。
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
两个数各由一个单链表表示,低位在表头、高位在表尾,求两数相加结果,也用单链表表示。
原题出处:https://oj.leetcode.com/problems/add-two-numbers/
大家可以自己写代码提交,验证正确性
分析:这道题的求解方法很直观。一个大循环,循环内部两个指针指向的内容与低位的进位相加,保留余数,继续进位。关键要处理的地方是两点。
1、 何时结束整个循环?
一开始陷入了惯性思维,当有一个链表为空之后,认为只要把剩下的链表直接加在已经求得的结果之后即可。这种想法是完全错了的,链表L1为空后,它还可能有进位,进位与L2还需要做加法操作,这可能又会产生新的进位。所以循环的结束条件应该是
L1不为空|| L2不为空
2、 循环结束后是否要做些什么?
循环结束后并不一定完事大吉,这时候还可能有进位等着加向最高位呢。但这时候L1 L2已经为空,我们必须新生成一个节点单独存储进位。
<span style="font-size:18px;">/** * 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 *l = new ListNode(-1); int sum = 0; int l1val, l2val; ListNode *p = l; while(l1 || l2) { l1val = (l1 == NULL) ? 0 : l1 -> val; l2val = (l2 == NULL) ? 0 : l2 -> val; sum += l1val + l2val; ListNode *q = new ListNode(sum % 10); sum /= 10; p -> next = q; p = q; if(l1) l1 = l1 -> next; if(l2) l2 = l2 -> next; } if(sum) { ListNode *q = new ListNode(sum); p -> next = q; } return l -> next; } };</span>
相关文章推荐
- LeetCode--Add Two Numbers(链表)
- LeetCode2. Add Two Numbers(链表加法)
- LeetCode 2 Add Two Numbers(链表操作)
- leetcode 2. Add Two Numbers 指针链表
- Leetcode解题-链表(2.2.1)AddTwoNumbers
- [Leetcode #2]Add Two Numbers 链表存储的两个正数相加
- Leetcode解题-链表(2.2.1)AddTwoNumbers
- LeetCode 2 Add Two Numbers(链表)
- [Leetcode #2]Add Two Numbers 链表存储的两个正数相加
- [LeetCode] Add Two Numbers 链表
- LeetCode-2-Add Two Numbers(链表)-Medium
- leetcode---Add Two Numbers---链表
- (leetcode)2. 两个链表相加Add Two Numbers--Java
- LeetCode-2-Add-Two-Numbers 链表
- leetcode Add Two Numbers(链表)
- Leetcode 第二章线性表--2.2 单链表--2.2.1 add two numbers--2017/7/25
- LeetCode之“链表”:Add Two Numbers
- 【LeetCode】链表相加 Add Two Numbers - Easy ++
- leetcode 5. 两个链表逐个元素相加 Add Two Numbers
- [C++]LeetCode 2: Add Two Numbers(链表逆序加法)