描述
假设链表中每一个节点的值都在 0 - 9 之间,那么链表整体就可以代表一个整数。
给定两个这种链表,请生成代表两个整数相加值的结果链表。
数据范围:0 \le n,m \le 10000000≤n,m≤1000000,链表任意值 0 \le val \le 90≤val≤9
要求:空间复杂度 O(n)O(n),时间复杂度 O(n)O(n)
例如:链表 1 为 9->3->7,链表 2 为 6->3,最后生成新的结果链表为 1->0->0->0。
示例1
输入:
[9,3,7],[6,3]
返回值:
{1,0,0,0}
示例2
输入:
[0],[6,3]
返回值:
{6,3}
思路
- 和大数加法类似模拟相加
- 不同之处
链表不同于数组、字符串结构,没有办法逆序访问的。因此需要对链表反转。链表反转固定代码
ListNode* ReverseList(ListNode* pHead) {
if(pHead == NULL)
return NULL;
ListNode* cur = pHead;
ListNode* pre = NULL;
while(cur != NULL){
//断开链表,要记录后续一个
ListNode* temp = cur->next;
//当前的next指向前一个
cur->next = pre;
//前一个更新为当前
pre = cur;
//当前更新为刚刚记录的后一个
cur = temp;
}
return pre;
}
整体代码
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;
//当前的next指向前一个
cur->next = pre;
//前一个更新为当前
pre = cur;
//当前更新为刚刚记录的后一个
cur = temp;
}
return pre;
}
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 ){
//链表不为空则取其值
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;
}
if(carry)
{
head->next = new ListNode(carry);
}
//结果反转回来
return ReverseList(res->next);
}
};