您的位置:首页 > 其它

lintcode,167,链表求和

2016-11-29 17:58 302 查看
你有两个用链表代表的整数,其中每个节点包含一个数字。数字存储按照在原来整数中相反的顺序,使得第一个数字位于链表的开头。写出一个函数将两个整数相加,用链表形式返回和。

解题思路:两个链表逐位相加,考虑进位,移动指针,最后还要考虑一次进位。

一刷没有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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  lintcode