概述
2019独角兽企业重金招聘Python工程师标准>>>
问题:
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 8 -> 0 -> 7
解决:
① 反转两个链表,相加之后再反转回来。
class Solution { //54ms
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
if (l2 == null) return l1;
ListNode p1 = reverse(l1);
ListNode p2 = reverse(l2);
int carry = 0;
ListNode header = new ListNode(-1);
ListNode cur = header;
while(p1 != null || p2 != null || carry != 0){
int x = p1 == null ? 0 : p1.val;
int y = p2 == null ? 0 : p2.val;
int sum = x + y + carry;
ListNode tmp = new ListNode(sum % 10);
carry = sum / 10;
tmp.next = cur.next;
cur.next = tmp;
cur = header;
if(p1 != null) p1 = p1.next;
if(p2 != null) p2 = p2.next;
}
return header.next;
}
public static ListNode reverse(ListNode head){
if (head == null || head.next == null) return head;
ListNode header = new ListNode(-1);
ListNode cur = head;
while(cur != null){
ListNode next = cur.next;
cur.next = header.next;
header.next = cur;
cur = next;
}
return header.next;
}
}
② 不反转,原地相加。首先计算长度,然后直接将对应的各位相加,最终,再扫描一次链表,更新每个节点的数值,加上进位。
class Solution {//54ms
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if(l1 == null || l2 == null) return null;
int len1 = 0;
int len2 = 0;
ListNode p1 = l1;
ListNode p2 = l2;
while(p1 != null){//计算链表的长度
p1 = p1.next;
len1 ++;
}
while(p2 != null){
p2 = p2.next;
len2 ++;
}
int len = Math.max(len1,len2);
ListNode pre = null;
ListNode head;
head = len1 > len2 ? l1 : l2;
while(len != 0){
int x = 0;
int y = 0;
if(len <= len1){
x = l1.val;
l1 = l1.next;
}
if(len <= len2){
y = l2.val;
l2 = l2.next;
}
len --;
head.val = x + y;
head.next = pre;
pre = head;
head = len1 > len2 ? l1 : l2;
}
head = pre;
pre = null;
int carry = 0;
while(head != null){
int cur = head.val + carry;
head.val = cur % 10;
carry = cur / 10;
ListNode temp = head.next;
head.next = pre;
pre = head;
head = temp;
}
if(carry != 0){
ListNode result = new ListNode(carry);
result.next = pre;
return result;
}
return pre;
}
}
转载于:https://my.oschina.net/liyurong/blog/1602612
最后
以上就是开心早晨为你收集整理的两个链表表示的数字相加 Add Two Numbers II的全部内容,希望文章能够帮你解决两个链表表示的数字相加 Add Two Numbers II所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复