445. Add Two Numbers II
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
此题和Add Two Numbers不同之处在于,此题的链表头是位高的位置,和之前那道题刚好相反。我思考了很久并没有想到用什么方法来解决,后来看提示说用栈来做,下面是我自己想出来的解法:
/**
* 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) {
Stack<Integer> s1 = new Stack<Integer>();
Stack<Integer> s2 = new Stack<Integer>();
Stack<Integer> s3 = new Stack<Integer>();
while(l1!=null){
s1.push(l1.val);
l1 = l1.next;
}
while(l2!=null){
s2.push(l2.val);
l2 = l2.next;
}
int carry = 0;
while(!s1.isEmpty()||!s2.isEmpty()||carry!=0){
if(!s1.isEmpty()){
carry+=s1.pop();
}
if(!s2.isEmpty()){
carry+=s2.pop();
}
s3.push(carry%10);
carry/=10;
}
ListNode dummy = new ListNode(0);
ListNode node = dummy;
while(!s3.isEmpty()){
node.val = s3.pop();
if(!s3.isEmpty()){
ListNode next = new ListNode(0);
node.next = next;
node = node.next;
}
}
return dummy;
}
}
但是后来看了答案的解法发现根本不需要用第三个栈,解法如下:
/**
* 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) {
Stack<Integer> s1 = new Stack<Integer>();
Stack<Integer> s2 = new Stack<Integer>();
while(l1!=null){
s1.push(l1.val);
l1 = l1.next;
}
while(l2!=null){
s2.push(l2.val);
l2= l2.next;
}
ListNode list = new ListNode(0);
int sum = 0;
while(!s1.isEmpty()||!s2.isEmpty()){
if(!s1.isEmpty()) sum+=s1.pop();
if(!s2.isEmpty()) sum+=s2.pop();
list.val = sum%10;
ListNode head = new ListNode(sum/10);
head.next = list;
list = head;
sum = sum/10;
}
return list.val==0?list.next:list;
}
}