假定用一个链表表示两个数,其中每个节点仅包含一个数字。假设这两个数的数字顺序排列,请设计一种方法将两个数相加,并将其结果表现为链表的形式。
给出 6->1->7 + 2->9->5
。即,617 + 295
。
返回 9->1->2
。即,912
。
本题类似于: 链表求和
只需要将链表以压栈的形式存入栈中,然后依次同栈顶取出每一个元素,进行上述 链表求和 的操作即可。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param l1: the first list
* @param l2: the second list
* @return: the sum list of l1 and l2
*/
public ListNode addLists2(ListNode l1, ListNode l2) {
if (l1 == null && l2 == null) {
return null;
}
Stack<Integer> stack1 = reverseNode(l1);
Stack<Integer> stack2 = reverseNode(l2);
ListNode point = new ListNode(0);
int carry = 0;
while (!stack1.isEmpty() && !stack2.isEmpty()) {
int val = stack1.pop() + stack2.pop() + carry;
carry = val / 10;
val = val % 10;
ListNode temp = new ListNode(val);
temp.next = point.next;
point.next = temp;
}
while (!stack1.isEmpty()) {
int val = stack1.pop() + carry;
carry = val / 10;
val = val % 10;
ListNode temp = new ListNode(val);
temp.next = point.next;
point.next = temp;
}
while (!stack2.isEmpty()) {
int val = stack2.pop() + carry;
carry = val / 10;
val = val % 10;
ListNode temp = new ListNode(val);
temp.next = point.next;
point.next = temp;
}
if (carry == 1) {
ListNode temp = new ListNode(1);
temp.next = point.next;
point.next = temp;
}
return point.next;
}
public Stack<Integer> reverseNode(ListNode temp){
Stack<Integer> record = new Stack<Integer>();
while(temp != null){
record.push(temp.val);
temp = temp.next;
}
return record;
}
}