Add Two Numbers
2015-10-03 22:57
183 查看
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
遍历两个链表,对每个节点依次相加即可,最后遍历完两个链表之后还要注意进位的值是否为0.
c++实现:
java实现:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
遍历两个链表,对每个节点依次相加即可,最后遍历完两个链表之后还要注意进位的值是否为0.
c++实现:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { int carry = 0; ListNode *head = NULL,*p = NULL; while(l1||l2){ if(l1){ carry += l1->val; ListNode *temp = l1; l1 = l1->next; free(temp); } if(l2){ carry += l2->val; ListNode *temp = l2; l2 = l2->next; free(temp); } ListNode *temp = new ListNode(carry%10); carry /= 10; if(p){ p->next = temp; p = p->next; } else{ head = p = temp; } } if(carry){ p->next = new ListNode(carry); } return head; }
java实现:
public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode ret = null; ListNode p = null; int carry = 0; while(l1!=null||l2!=null){ int x = 0,y = 0,sum = 0; if(l1!=null){ x = l1.val; l1 = l1.next; } if(l2!=null){ y = l2.val; l2 = l2.next; } sum = x+y+carry; carry = sum/10; ListNode temp = new ListNode(sum%10); if(ret==null){ ret = temp; p = ret; } else{ p.next = temp; p = p.next; } } if(carry>0){ p.next = new ListNode(carry); } return ret; }
相关文章推荐
- 剑指offer—复杂链表的复制
- 安卓控件使用系列33:ViewPager多页面滑动控件的使用方法2
- linux中文件属性和权限修改命令chgrp|chown|chmod介绍
- 百度搜索这些词:(百度搜索特效,好玩)
- 设计模式--命令模式(Command)
- mac上maven的配置
- 弱校联盟国庆第二天 D题
- [转载] 程序员如何成功追到女神?
- Tutorial: Using a URDF in Gazebo
- 从RTTI谈C++的向下转型
- 信息的表示和处理 第三周9.28~10.4
- 【特种兵PPT教程】如何给你的PPT2013文件加密?
- Gas Station - LeetCode 134
- IOS开发-属性动画和关键帧动画的使用
- 5、Hibernate的延迟加载
- mac上mysql配置-解决连接127.0.0.1错误问题
- jquery 实现邮箱输入自动提示功能:(一)
- 张氏web漏洞检查工具发布-英文名:Mr.Zhang Web Leak Scanner GUI
- 剑指offer—二叉树中和为某一值的路径
- linux配置网络办法