一、题目描述
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.
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7
二、题解
方法一:栈
- 由于链表给的是顺序数字,加法需要从后往前。所以需要把每一位数字拿出来先。
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int ca = 0;
Stack<Integer> st1 = new Stack<>();
Stack<Integer> st2 = new Stack<>();
ListNode t1 = l1, t2 = l2;
while (t1 != null) {
st1.push(t1.val);
t1 = t1.next;
}
while (t2 != null) {
st2.push(t2.val);
t2 = t2.next;
}
ListNode head = null;
while (!st1.isEmpty() || !st2.isEmpty() || ca > 0) {
int n1 = st1.isEmpty() ? 0 : st1.pop();
int n2 = st2.isEmpty() ? 0 : st2.pop();
int sum = n1 + n2 + ca;
ListNode t = new ListNode(sum%10);
t.next = head;
head = t;
ca = sum / 10;
}
return head;
}
复杂度分析
- 时间复杂度: ,
- 空间复杂度: ,