题目:
假设链表中每一个节点的值都在 0 - 9 之间,那么链表整体就可以代表一个整数。
给定两个这种链表,请生成代表两个整数相加值的结果链表。
例如:链表 1 为 9->3->7,链表 2 为 6->3,最后生成新的结果链表为 1->0->0->0。
示例1
输入:
[9,3,7],[6,3]返回值:
{1,0,0,0}备注:
1≤n,m≤1061 \leq n, m \leq 10^61≤n,m≤106 0≤ai,bi≤90 \leq a_i, b_i \leq 90≤ai,bi≤9
思路:最近超级喜欢用栈,所以这里用2个栈把链表中的数放进去,然后进行加法运算,最后把结果放到站里,刚好满足先进后出的特性,之后就把栈中的数依次赋值给新建的链表就可以了!
但是!新建链表时,一定一定一定!!!要注意每次都要新建一个节点!!!!!!因为是链表!这样子的:
ListNode answ = new ListNode(temp.pop());
ListNode node = answ;
while(!temp.isEmpty()){
node.next = new ListNode(temp.pop());//新建节点!!!!
node = node.next;
}
最后附上代码:
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> num1 = new Stack<>();
Stack<Integer> num2 = new Stack<>();
Stack<Integer> temp = new Stack<>();
ListNode answ = null;
if(head1 == null && head2 == null){
return null;
}else if(head1 == null && head2 != null){
answ = head2;
}else if(head1 != null && head2 == null){
answ = head1;
}
while(head1 != null){
num1.push(head1.val);
head1 = head1.next;
}
while(head2 != null){
num2.push(head2.val);
head2 = head2.next;
}
int overflow = 0;
while(!num2.isEmpty() && !num1.isEmpty()){
int a = num1.pop();
int b = num2.pop();
int ans = (a + b + overflow) % 10;
overflow = (a + b + overflow) / 10;
temp.push(ans);
}
while(!num1.isEmpty()){
int a1 = num1.pop();
int ans1 = (a1 + overflow) % 10;
overflow = (a1 + overflow) / 10;
temp.push(ans1);
}
while(!num2.isEmpty()){
int b2 = num2.pop();
int ans2 = (b2 + overflow) % 10;
overflow = (b2 + overflow) / 10;
temp.push(ans2);
}
if(overflow > 0){
temp.push(overflow);
}
answ = new ListNode(temp.pop());
ListNode node = answ;
while(!temp.isEmpty()){
node.next = new ListNode(temp.pop());
node = node.next;
}
return answ;
}
}