LintCode之167 链表求和
2016-07-27 20:07
387 查看
题目来源:链表求和
题目描述:
你有两个用链表代表的整数,其中每个节点包含一个数字。数字存储按照在原来整数中相反的顺序,使得第一个数字位于链表的开头。写出一个函数将两个整数相加,用链表形式返回和。
样例:
给出两个链表 3->1->5->null 和 5->9->2->null,返回 8->0->8->null
Java代码:
题目描述:
你有两个用链表代表的整数,其中每个节点包含一个数字。数字存储按照在原来整数中相反的顺序,使得第一个数字位于链表的开头。写出一个函数将两个整数相加,用链表形式返回和。
样例:
给出两个链表 3->1->5->null 和 5->9->2->null,返回 8->0->8->null
Java代码:
public ListNode addLists(ListNode l1, ListNode l2) { // write your code here int jinwei=0; if (l1==null) { return l2; } if (l2==null) { return l1; } ListNode result = new ListNode(0),head = result; while (l1!=null||l2!=null) { if (l1==null) { result.val = l2.val+jinwei; jinwei=0; if(l2.next!=null) result.next = new ListNode(0); result = result.next; l2=l2.next; } else if (l2==null) { result.val = l1.val+jinwei; jinwei = 0; if(l1.next!=null) result.next = new ListNode(0); result = result.next; l1=l1.next; } else if (l1!=null&&l2!=null) { if (l1.val+l2.val+jinwei>=10) { result.val = (l1.val+l2.val+jinwei); jinwei = 1; } else { 99d7 result.val = l1.val + l2.val + jinwei; jinwei = 0; } if(l1.next!=null||l2.next!=null||jinwei==1) result.next = new ListNode(0); result = result.next; l1=l1.next; l2=l2.next; } } if(jinwei==0) return head; else { result.val=1; return head; } }
相关文章推荐
- 安卓在两个控件中间画一条竖线
- BFC
- 做好这些面试准备,你还担心什么?
- 【Mysql】存储emoji表情报错(Incorrect string value: '\xF0\x9F\x98\x82\xF0\x9F...')的解决方案
- ★ AutoCAD 2015 必备优化★ (使用软件自带的"将设置重置为默认值"功能,会还原以下所有优化为软件默认值)
- SQLiteOpenHelper类的onCreate方法什么时候被执行--只有database.db不存在的时候
- HTML5 Web API:postMessage
- HDU 4588 Count The Carries(规律)
- POJ 3087
- Mini2440烧写Linux系统
- hashmap两种遍历总结!
- spark配置IntelliJ开发环境详解
- [HihoCoder]#1289 : 403 Forbidden
- 2016多校联合3
- POJ 1573 Robot Motion(模拟水题)
- 69. JPA实体Bean的生命周期【从零开始学Spring Boot】
- R语言之机器学习程序包(更新)
- Dynamics CRM 错误 问题排查
- 中软Java学习笔记第二天
- emmc/sd 核心层解析