假设链表中每一个节点的值都在 0 - 9 之间,那么链表整体就可以代表一个整数。 给定两个这种链表,请生成代表两个整数相加值的结果链表。 例如:链表 1 为 9->3->7,链表 2 为 6->3,最后生成新的结果链表为 1->0->0->0。
设立两个堆栈,一个存放head1,一个存放head2,再依次出栈求和并计算进位,最后将每一位添加至新链表的前面。
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
public ListNode addInList (ListNode head1, ListNode head2) {
// write code here
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
if(head1 == null)return head2;
if(head2 == null)return head1;
while(head1 != null){
stack1.push(head1.val);
head1 = head1.next;
}
while(head2 != null){
stack2.push(head2.val);
head2 = head2.next;
}
int c = 0;
int sum = 0;
ListNode pre = null;
while(!stack1.isEmpty() || !stack2.isEmpty() || c>0){
int val1 = stack1.isEmpty() == true?0:stack1.pop();
int val2 = stack2.isEmpty() == true?0:stack2.pop();
sum = val1+val2+c;
c = sum/10;
ListNode temp = new ListNode(sum%10);
temp.next = pre;
pre = temp;
}
return pre;
}
}