难度:普遍
题干:
You are given two non-empty linked lists representing two non-negative integers. 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.You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
我的解答(Java)
/**
* 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) {
ListNode rsHead = new ListNode(0);
ListNode node = rsHead ;
int up = 0 ; //进位加1或者不进位
while(l1 != null || l2 != null || up != 0){
if(node.next != null){
node = node.next;
}
node.val = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + up ;
up = node.val/10 ;
node.val = node.val%10 ;
node.next = new ListNode(0);
l1 = l1 == null ? l1 :l1.next ;
l2 = l2 == null ? l2 :l2.next ;
}
node.next = null ;
return rsHead ;
}
}
时间复杂度和空间复杂度均为O(n)。如果l1、l2节点个数相差很多,需要整个遍历最多节点的list,考虑到如果其中一个节点已经为NULL,只需要把另外一个节点挂载起来即可(没有进位的情况下),可以节省时间和空间。
修改后的解答(Java)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
private void addUp(ListNode head){
while(head != null){
if(head.val == 9){
head.val = 0 ;
if(head.next != null){
head = head.next;
}else{
head.next = new ListNode(1);
break;
}
}else{
head.val++ ;
break;
}
}
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode rsHead = l1 ;
ListNode node = rsHead ;
int up = 0 ; //进位加1或者不进位
while(l1 != null || l2 != null || up != 0){
node.val = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + up ;
up = node.val/10 ;
node.val = node.val%10 ;
l1=l1.next;
l2=l2.next;
if(l1 == null || l2 == null ){
if(up == 0){
ListNode l = l1 == null ? l2:l1;
node.next = l ;
}else{
ListNode l = l1 == null ? l2:l1;
if(l != null){
node.next = l ;
addUp(l);
}else{
node.next = new ListNode(1);
}
}
break;
}else{
node = node.next ;
}
}
return rsHead ;
}
}
时间复杂度O(n),一般情况只需要遍历最短的一个ListNode即可。空间复杂度O(1),但是代码长度变长了,可读性也下降了。后续有时间再优化吧。