原题链接: https://leetcode.com/problems/add-two-numbers-ii/
1. 题目介绍
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.
给出2个非空的链表,代表两个非负整数。整数的最高位是链表的第一个节点。每个节点的value值只有一位。将这两个数相加,然后返回和的链表。
你可以假设这两个数不会包含任何前导零,除非它是零本身。
更进一步,如果假设你不能修改输入的链表呢?也就是,不能翻转链表。
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7
7243 + 564 = 7807
2. 解题思路
这个题和 2. Add Two Numbers 非常像,不同的地方是链表示整数的方式, 2. Add Two Numbers 中的链表是从低位到高位,而本题中的链表是从高位到低位。
链表只能从前向后遍历,整数加法只能先加低位后加高位。所以我们在遍历链表的时候,可以使用堆栈来存储链表中的节点。从前向后遍历链表,从高位到低位将数放入堆栈。待所有节点都放入堆栈后,再借助堆栈“先入后出,后入先出” 的特性,先弹出计算整数的低位,然后再计算整数的高位。
实现代码
/**
* 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) {
Stack<Integer> a = ListToStack(l1);
Stack<Integer> b = ListToStack(l2);
Stack<Integer> ans = new Stack<Integer>();
ListNode assist = new ListNode(0);
int jinwei = 0;
while( (!a.empty()) || (!b.empty()) )
{
int x = (a.empty() == true ? 0 : a.pop() );
int y = (b.empty() == true ? 0 : b.pop() );
int sum = x + y + jinwei;
ans.push(sum%10);
jinwei = sum/10;
}
//如果还有进位,则进到最高位,需要在堆栈中再增加一位
if(jinwei != 0){
ans.push(jinwei);
}
ListNode cur = assist;
while( !ans.empty() ){
cur.next = new ListNode(ans.pop());
cur = cur.next;
}
return assist.next;
}
//将链表中的节点都放入堆栈,先放入高位,后放入低位
public Stack<Integer> ListToStack(ListNode root){
ListNode cur = root;
Stack<Integer> s = new Stack<Integer>();
while(cur != null){
s.push(cur.val);
cur = cur.next;
}
return s;
}
}