lintcode,167,链表求和
2016-11-29 17:58
302 查看
你有两个用链表代表的整数,其中每个节点包含一个数字。数字存储按照在原来整数中相反的顺序,使得第一个数字位于链表的开头。写出一个函数将两个整数相加,用链表形式返回和。
解题思路:两个链表逐位相加,考虑进位,移动指针,最后还要考虑一次进位。
一刷没有ac,细节没有考虑全。
二刷ac
解题思路:两个链表逐位相加,考虑进位,移动指针,最后还要考虑一次进位。
一刷没有ac,细节没有考虑全。
二刷ac
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { /** * @param l1: the first list * @param l2: the second list * @return: the sum list of l1 and l2 */ public ListNode addLists(ListNode l1, ListNode l2) { if(l1 == null && l2 == null) return null; ListNode head = new ListNode(0); ListNode tail = head; int carry = 0; while(l1 != null && l2 != null){ int value = carry + l1.val + l2.val; carry = value / 10; value = value % 10; ListNode node = new ListNode(value); tail.next = node; tail = tail.next; l1 = l1.next; l2 = l2.next; } while(l1 != null){ int value = carry + l1.val; carry = value / 10; value = value % 10; ListNode node = new ListNode(value); tail.next = node; tail = tail.next; l1 = l1.next; } while(l2 != null){ int value = carry + l2.val; carry = value / 10; value = value % 10; ListNode node = new ListNode(value); tail.next = node; tail = tail.next; l2 = l2.next; } if(carry > 0){ ListNode node = new ListNode(carry); tail.next = node; tail = tail.next; } return head.next; } }
相关文章推荐
- python_lintcode_167链表求和
- lintcode-167-链表求和
- LintCode_167_链表求和
- LintCode_167_链表求和
- [Lintcode] #167 链表求和
- 【LintCode-167】链表求和(Java实现)
- lintcode(221)链表求和 II
- 链表求和 II-LintCode
- [LintCode]167.链表求和
- 167 - 链表求和
- LintCode【简单】167. 链表求和 。代码及思路
- 链表求和-LintCode
- LintCode-[中等] 221. 链表求和 II
- LintCode之167 链表求和
- lintcode-链表求和
- [LintCode]链表求和
- 链表求和(LintCode)
- LintCode-链表求和
- LintCode | 167. 链表求和
- lintcode 链表求和