您的位置:首页 > 其它

Add Two Numbers

2015-08-06 14:02 281 查看
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

题目解析:有进位的链表合并,主要是考虑最后一次进位的情况,比如【2,7】【3,7】——>【5,1,4】

解法:链表问题一定要注意是否是空指针,然后在合并中分为3类处理,俩个链表均有元素,A链表完结,B链表完结,AC代码如下

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
// 安全性检查
if (l1 == null || l2 == null) {
return null;
}
// 考虑有进位
int carry = 0;
ListNode result = new ListNode(0);
ListNode ponit = result;
//分三种情况讨论比较好理解
while (l1 != null && l2 != null) {
int sum = l1.val + l2.val+carry;
ponit.next = new ListNode(sum % 10);
carry = sum / 10;
l1 = l1.next;
l2 = l2.next;
ponit = ponit.next;
}
while (l1 != null) {
int sum = carry + l1.val;
ponit.next = new ListNode(sum % 10);
carry = sum / 10;
l1 = l1.next;
ponit = ponit.next;
}

while (l2 != null) {
int sum = carry + l2.val;
ponit.next = new ListNode(sum % 10);
carry = sum / 10;
l2 = l2.next;
ponit = ponit.next;
}
//防止最后一位仍有进位
if(carry!=0){
ponit.next = new ListNode(carry);
}

return result.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: