假设链表中每一个节点的值都在 0 - 9 之间,那么链表整体就可以代表一个整数。
给定两个这种链表,请生成代表两个整数相加值的结果链表。
数据范围:0≤𝑛,𝑚≤1000000,链表任意值 0≤𝑣𝑎𝑙≤9
要求:空间复杂度 𝑂(𝑛),时间复杂度 𝑂(𝑛)
public class Solution {
//反转链表
public ListNode ReverseList(ListNode pHead) {
if(pHead == null)
return null;
ListNode cur = pHead;
ListNode pre = null;
while(cur != null){
ListNode temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
public ListNode addInList (ListNode head1, ListNode head2) {
if(head1 == null)
return head2;
if(head2 == null)
return head1;
head1 = ReverseList(head1);
head2 = ReverseList(head2);
ListNode res = new ListNode(-1);
ListNode head = res;
int carry = 0;
while(head1 != null || head2 != null || carry != 0){
int val1 = head1 == null ? 0 : head1.val;
int val2 = head2 == null ? 0 : head2.val;
int temp = val1 + val2 + carry;
carry = temp / 10;
temp %= 10;
head.next = new ListNode(temp);
head = head.next;
if(head1 != null)
head1 = head1.next;
if(head2 != null)
head2 = head2.next;
}
return ReverseList(res.next);
}
}