链表——将两个链表上的数字相加(考虑进位)并将和放入新链表
2016-05-09 19:47
357 查看
题目:
给予两个链表,每个节点中有一个0-9的数字,将相应位置上的数字相加并进位,用新的链表存储其和。
例如:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
思路:
可能的情况有:
1.两个链表first和second都没有到表尾;
2.一个到表尾,另一个没有;
3.两个都到表尾;
注意!当一个链表到结尾或者两个链表都到结尾时,但是carry不为0,程序仍不能结束;
给予两个链表,每个节点中有一个0-9的数字,将相应位置上的数字相加并进位,用新的链表存储其和。
例如:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
思路:
可能的情况有:
1.两个链表first和second都没有到表尾;
2.一个到表尾,另一个没有;
3.两个都到表尾;
注意!当一个链表到结尾或者两个链表都到结尾时,但是carry不为0,程序仍不能结束;
public ListNode addTwoNumbers(ListNode first, ListNode second) { if(first==null) return second; if(second==null) return first; int sum=0;//first和second对应结点的和,值为(0-9); int carry=0;//first和second对应结点求和后对应的进位,值为(0或1); ListNode head=new ListNode(0); ListNode cur=head; while(first != null||second != null||carry != 0) { int num1=0; int num2=0; if(first!=null) { num1=first.val; first=first.next; } if(second!=null) { num2=second.val; second=second.next; } sum=(carry+num1+num2)%10; ListNode temp=new ListNode(sum); cur.next=temp; cur=cur.next; carry=(carry+num1+num2)/10; } return head.next; }
相关文章推荐
- Jmeter访问HTTPS请求
- 计算机系统
- 网络编程
- httpOnly实现防止XSS时避免JavaScript读取cookie
- HashTable与HashMap的区别
- Activity、Task、应用和进程
- 一篇关于程序员的文章
- 揭开RecyclerView的神秘面纱(一):RecyclerView的基本使用
- 【转】【C#】判断两个文件是否相同
- 编译适用于TP-Link WR703N的OpenWRT固件
- android集成genymotion
- Android Service与Activity之间通信的几种方式
- JAVA基础之——HashSet中是如何判断元素是否重复的
- 将Eclipse项目导入Android Studio出现中文乱码的问题
- poj1159 dp(滚动数组优化)
- C++基础知识 动态链接库和静态链接库
- JDk安装及配置
- 我的android服务器端,看一下是什么问题?
- 公路隧道通风设计分析系统图片
- HDOJ2089