题目
原始地址:https://leetcode.com/problems/add-two-numbers-ii/#/description
/**
* 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) {
}
}
描述
给定两个单链表,代表两个非负整数,链表的头节点代表数的最高位。求这两个数的和并且以相同的链表形式返回。
分析
一种常用的解法是分别将两个链表反转,低位在前高位在后,这样符合加法的常规做法。但是本题目要求不得修改原链表,那么我们就新申请两个栈用来做一下反转,逐位相加后生成新链表作为结果返回。
解法
/**
* 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<>(), s2 = new Stack<>(), s3 = new Stack<>();
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.empty() || !s2.empty() || carry != 0) {
int v1 = s1.empty() ? 0 : s1.pop();
int v2 = s2.empty() ? 0 : s2.pop();
int sum = v1 + v2 + carry;
s3.push(sum % 10);
carry = sum / 10;
}
ListNode head = new ListNode(0), node = head;
while (!s3.empty()) {
node.next = new ListNode(s3.pop());
node = node.next;
}
return head.next;
}
}