假设链表中每一个节点的值都在 0 - 9 之间,那么链表整体就可以代表一个整数。给定两个这种链表,请生成代表两个整数相加值的结果链表。例如:链表 1 为 9->3->7,链表 2 为 6->3,最后生成新的结果链表为 1->0->0->0。
解题
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> s1 = new Stack();//用来存储两个链表的数据
Stack<Integer> s2 = new Stack();
while (head1 != null) {//将head1的元素放入栈1
s1.push(head1.val);
head1 = head1.next;
}
while (head2 != null) { //将head2的元素放入栈2
s2.push(head2.val);
head2 = head2.next;
}
ListNode res = null; // 用于返回的链表
int cnt = 0; //如果两个值的加和>10,就会产生进位,这个用来存储进位
while (!s1.empty() || !s2.empty()) { // 从两个栈中各取一位
int x1 = s1.isEmpty() ? 0 : s1.pop();
int x2 = s2.isEmpty() ? 0 : s2.pop();
int sum = x1 + x2 + cnt;//当前这一位的总和
cnt = sum / 10;//查看当前加和是否有进位
///进行当前节点的插入
ListNode tempNode = new ListNode(sum % 10);
tempNode.next = res;
res = tempNode;
}
if(cnt > 0){
ListNode tempNode = new ListNode(cnt);
tempNode.next = res;
res = tempNode;
}
return res;
}
}