题目:
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
给了俩链表,要求把两个链表表示的数字加起来。因为要倒着加,所以可以先把链表里所有元素push到stack里然后一个个pop出来。为了生成最终的链表,我们可以先new一个dummy,dummy的右边表示已经生成好的部分,每次产生结果就可以直接new一个新节点,然后令这个新节点的next=dummy。非常简单易懂。但是自己写的时候还是有点小问题:一个是while循环截止条件,我们做这个操作一直到没得加为止,那没得加就是两个list都用完了,并且还没有carry!在while里面处理的时候可以直接,如果stack1不为空就加入stack1.pop,如果stack2不为空就加入stack2.pop,最后加上carry。这题主要是细节问题比较多,时间复杂度O(n)吧。
Runtime: 4 ms, faster than 43.33% of Java online submissions for Add Two Numbers II.
Memory Usage: 39.2 MB, less than 96.37% of Java online submissions for Add Two Numbers II.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
Deque<Integer> stack1 = new ArrayDeque<>();
Deque<Integer> stack2 = new ArrayDeque<>();
while (l1 != null) {
stack1.push(l1.val);
l1 = l1.next;
}
while (l2 != null) {
stack2.push(l2.val);
l2 = l2.next;
}
int carry = 0;
ListNode dummy = null;
while (!stack1.isEmpty() || !stack2.isEmpty() || carry != 0) {
int tempSum = 0;
if (!stack1.isEmpty()) {
tempSum += stack1.pop();
}
if (!stack2.isEmpty()) {
tempSum += stack2.pop();
}
tempSum += carry;
carry = tempSum / 10;
tempSum %= 10;
ListNode newNode = new ListNode(tempSum);
newNode.next = dummy;
dummy = newNode;
}
return dummy;
}
}