题解 | #两个链表生成相加链表#
两个链表生成相加链表
http://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
1.首先把两个链表都反转
2.从头开始两个链表相加
3.反转相加后的链表
public ListNode addInList2(ListNode head1, ListNode head2) {
if (head1 == null) return head2;
if (head2 == null) return head1;
ListNode pre1 = null;
ListNode next1;
while (head1 != null) {
next1 = head1.next;
head1.next = pre1;
pre1 = head1;
head1 = next1;
}
ListNode pre2 = null;
ListNode next2;
while (head2 != null) {
next2 = head2.next;
head2.next = pre2;
pre2 = head2;
head2 = next2;
}
ListNode newHead = new ListNode(0);
ListNode newTemp = newHead;
int c = 0;
while (pre1 != null || pre2 != null) {
int a = 0;
int b = 0;
if (pre1 != null) {
a = pre1.val;
pre1 = pre1.next;
}
if (pre2 != null) {
b = pre2.val;
pre2 = pre2.next;
}
newTemp.next = new ListNode((a + b + c) % 10);
newTemp = newTemp.next;
c = (a + b + c) / 10;
}
if (c != 0) {
newTemp.next = new ListNode(c);
}
ListNode head = newHead.next;
ListNode pre = null;
ListNode next = null;
while (head != null) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}