题解 | 链表相加(二)
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
1.通过反转链表的方式,可以让他们从头开始算
2.累加完后,再次反转。
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
public ListNode addInList (ListNode head1, ListNode head2) {
ListNode temp = fanzhuan(head1);
ListNode new2 = fanzhuan(head2);
ListNode cur = new ListNode(-1);
ListNode pre = cur;
int i=0;
while(temp !=null || new2 != null || i==1) {
int val = i;
if (temp != null) {
val += temp.val;
temp = temp.next;
}
if (new2 != null) {
val += new2.val;
new2 = new2.next;
}
i = 0;
if (val >= 10) {
i = 1;
val -= 10;
}
pre.next = new ListNode(val);
pre = pre.next;
}
return fanzhuan(cur.next);
}
public ListNode fanzhuan(ListNode node) {
ListNode cur = node;
ListNode pre = null;
while(cur != null){
ListNode temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
}