leetcode第二题add two numbers
来源:互联网 发布:mac os回到桌面 编辑:程序博客网 时间:2024/06/14 15:20
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
题目本身理解不难,就是是链表把2个数的每一位存起来,我们加起来就行了,要考虑的就是进位。
感觉就考了2个东西,一个是思维严谨,一个是链表操作。
(1)链表操作。
不怕丢人,之前学过链表,总以为很简单,其实写过才会有感觉把。
一开始我是这么干的
ListNode *pnext=new ListNode(shu);……pnext=pnext->next;
然而pnext->next为空(我都不知道当时我哪根筋不正常了),这样写的话内存还没释放,pnext又指向一个NULL,(并没有对pnext->next赋值)。
正确的应该是:
第一次对pnext赋值时候
ListNode *pnext=new ListNode(shu);
之后应该先把pnext->next赋值好
pnext->next=new ListNode(shu);
然后pnext指针指向它的下一个next指针。
pnext=pnext->next;
(2)思维严谨。
while(l1!=NULL && l2!=NULL) { <span style="color:#FF0000;">shu=(l1->val+l2->val)%10;</span> pnode=new ListNode(shu<span style="color:#FF0000;">+up)</span>; up=(l1->val+l2->val+up)/10; if(resulist==NULL) { resulist=pnext=pnode; } else { pnext->next=pnode; pnext=pnext->next; } l1=l1->next; l2=l2->next; }说到这思维,其实应该是数学知识了。
上面代码红色部分就很有问题。
shu指的是当前链表应该打的数,比如9+1的话我们应该打印0。
up指的是进位。
这里shu除了加上l1和l2的值(val)还应该加上进位再向10取余,而我一开始是l1和l2的值加起来取余,然后在建立pnode时候加上进位,而且我们在做加法也是需要加上进位的。
while(l1!=NULL && l2!=NULL) { shu=(l1->val+l2->val<span style="color:#FF0000;">+up</span>)%10; pnode=new ListNode(shu); up=(l1->val+l2->val+up)/10; if(resulist==NULL) { resulist=pnext=pnode; } else { pnext->next=pnode; pnext=pnext->next; } l1=l1->next; l2=l2->next; }
还有要考虑的是:
①哪个链表多了几位需要怎么办。
②两个相同位数的链表加起来超过了原来位数能表达的范围怎么办。(这时候两个链表循环都没了)
0 0
- leetcode 第二题Add Two Numbers java
- Add Two Numbers LeetCode第二题
- leetcode第二题add two numbers
- leetcode第二题Add Two Numbers
- leetcode第二题<Add Two Numbers>
- C# LeetCode第二题 Add Two Numbers
- 第二题:Add Two Numbers
- LeetCode: Add Two Numbers
- LeetCode: Add Two Numbers
- [LeetCode]Add Two Numbers
- LeetCode Add Two Numbers
- Leetcode: Add Two Numbers
- LeetCode : Add Two Numbers
- LeetCode Add Two Numbers
- [LeetCode] Add Two Numbers
- Leetcode : Add Two Numbers
- 【leetcode】Add Two Numbers
- [LeetCode]Add Two Numbers
- spring quartz定时任务
- 第13周项目1Kruskal算法的验证
- C++primer plus第六版课后编程练习答案11.3
- 直接选择排序
- zzuli 1785: 学渣的逆袭
- leetcode第二题add two numbers
- 【C语言提高11】野指针
- 第13周SHH数据结构-【项目5-拓扑排序算法的验证 】
- 第14周、项目2—二叉树排序树中查找的路径
- Git .gitignore文件忽略
- JSBadgeView
- 使用PropertyChangeSupport监听变量变化
- 十四周 项目一 验证算法(折半查找)
- AT+CNMI