LeetCode Add Two Numbers II

时间:2023-09-23 15:41:26

原题链接在这里:https://leetcode.com/problems/add-two-numbers-ii/

题目:

You are given two linked lists representing two non-negative numbers. 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

题解:

类似Add Two Numbers.

可看成是Add Two NumbersReverse Linked List的综合. 先reverse在逐个add, 最后把结果reverse回来.

Time Complexity: O(n).

Space: O(1).

AC Java:

 /**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
l1 = reverse(l1);
l2 = reverse(l2); ListNode dummy = new ListNode(0);
ListNode cur = dummy;
int carry = 0; while(l1 != null || l2!= null){
if(l1 != null){
carry += l1.val;
l1 = l1.next;
} if(l2 != null){
carry += l2.val;
l2 = l2.next;
} cur.next = new ListNode(carry%10);
carry /= 10;
cur = cur.next;
} if(carry != 0){
cur.next = new ListNode(carry);
} ListNode head = dummy.next;
dummy.next = null;
return reverse(head);
} private ListNode reverse(ListNode head){
if(head == null || head.next == null){
return head;
} ListNode tail = head;
ListNode cur = head;
ListNode pre;
ListNode temp;
while(tail.next != null){
pre = cur;
cur = tail.next;
temp = cur.next;
cur.next = pre;
tail.next = temp;
} return cur;
}
}

也可以使用两个stack把list 1 和 list 2 分别压进去. 再pop出来相加放到new list的head位置.

Time Complexity: O(n). 压stack用了O(n), pop后相加用了O(n).

Space: O(n). stack用了O(n). result list用了O(n).

AC 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) {
if(l1 == null){
return l2;
}
if(l2 == null){
return l1;
} Stack<Integer> stk1 = new Stack<Integer>();
Stack<Integer> stk2 = new Stack<Integer>();
while(l1 != null){
stk1.push(l1.val);
l1 = l1.next;
}
while(l2 != null){
stk2.push(l2.val);
l2 = l2.next;
} ListNode dummy = new ListNode(0);
int carry = 0;
while(!stk1.isEmpty() || !stk2.isEmpty()){
if(!stk1.isEmpty()){
carry += stk1.pop();
}
if(!stk2.isEmpty()){
carry += stk2.pop();
}
ListNode cur = new ListNode(carry%10);
cur.next = dummy.next;
dummy.next = cur;
carry /= 10;
}
if(carry != 0){
ListNode cur = new ListNode(1);
cur.next = dummy.next;
dummy.next = cur;
}
return dummy.next;
}
}