题解 | #链表相加(二)#
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
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) {
if (head1 == null) {
return head2;
}
if (head2 == null) {
return head1;
}
// write code here
ListNode h1 = reverse(head1);
ListNode h2 = reverse(head2);
int carry = 0;
ListNode res = new ListNode(-1);
ListNode cur = res;
while (h1 != null || h2 != null) {
int v1 = h1 == null ? 0 : h1.val;
int v2 = h2 == null ? 0 : h2.val;
int sum = v1 + v2 + carry;
cur.next = new ListNode(sum % 10);
carry = sum / 10;
cur = cur.next;
h1 = h1 != null ? h1.next : null;
h2 = h2 != null ? h2.next : null;
}
if (carry > 0) {
cur.next = new ListNode(1);
cur = cur.next;
}
return reverse(res.next);
}
private ListNode reverse(ListNode head) {
if (head == null) {
return null;
}
ListNode pre = null;
while (head != null) {
ListNode next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
}
/*
* 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) {
if (head1 == null) {
return head2;
}
if (head2 == null) {
return head1;
}
// write code here
ListNode h1 = reverse(head1);
ListNode h2 = reverse(head2);
int carry = 0;
ListNode res = new ListNode(-1);
ListNode cur = res;
while (h1 != null || h2 != null) {
int v1 = h1 == null ? 0 : h1.val;
int v2 = h2 == null ? 0 : h2.val;
int sum = v1 + v2 + carry;
cur.next = new ListNode(sum % 10);
carry = sum / 10;
cur = cur.next;
h1 = h1 != null ? h1.next : null;
h2 = h2 != null ? h2.next : null;
}
if (carry > 0) {
cur.next = new ListNode(1);
cur = cur.next;
}
return reverse(res.next);
}
private ListNode reverse(ListNode head) {
if (head == null) {
return null;
}
ListNode pre = null;
while (head != null) {
ListNode next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
}