NC40 两个链表生成相加链表
假设链表中每一个节点的值都在 0 - 9 之间,那么链表整体就可以代表一个整数。
给定两个这种链表,请生成代表两个整数相加值的结果链表。
数据范围:,链表任意值
要求:空间复杂度,时间复杂度
例如:链表 1 为 9->3->7,链表 2 为 6->3,最后生成新的结果链表为 1->0->0->0。
思路:首先需要将各位对齐,即个位对齐个位,十位对齐十位...此时需要反转链表。链表反转后,对各位相加,需要一个进位标识符carry记录每次相加是否有进位。链表遍历完后,需要判断carry是否为0,不为0则需要在最后加上进位。最后将生成的链表反转即是最后的结果。
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
if(head1 == null) {
return head2;
}
if(head2 == null) {
return head1;
}
head1 = rev(head1);
head2 = rev(head2);
ListNode dummy = new ListNode(-1);
ListNode pre = dummy;
int carry = 0;
while(head1 != null || head2 != null) {
int x = carry;
if(head1 != null) {
x += head1.val;
head1 = head1.next;
}
if(head2 != null) {
x += head2.val;
head2 = head2.next;
}
pre.next = new ListNode(x%10);
carry = x / 10;
pre = pre.next;
}
if(carry != 0) {
pre.next = new ListNode(carry);
}
return rev(dummy.next);
}
public ListNode rev(ListNode head) {
ListNode pre = head, cur = head.next;
pre.next = null;
while(cur != null) {
ListNode node = cur.next;
cur.next = pre;
pre = cur;
cur = node;
}
return pre;
}
}