步骤
1、 任意一个链表为空,返回另一个链表就行了,因为链表为空相当于0,0加任何数为0,包括另一个加数为0的情况。
2、反转两个待相加的链表,反转过程可以参考反转链表
3、设置返回链表的链表头,设置进位carry=0
4、从头开始遍历两个链表,直到两个链表节点都为空,carry也不为1.每次取出不为空的链表节点值,为空就设置为0,将两个数字与carry相加,然后查看是否进位,将进位后的结果(对10取模)加入新的链表节点,连接在返回链表后面,并继续往后遍历
5、返回前将结果链表再反转回来
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
#include <stdio.h>
#include <stdlib.h>
struct ListNode * reverseList(struct ListNode *head)
{
if (head == NULL) {
return NULL;
}
struct ListNode *cur = head;
struct ListNode *pre = NULL;
struct ListNode *temp = NULL;
while (cur != NULL) {
temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
struct ListNode* addInList(struct ListNode* head1, struct ListNode* head2 ) {
// write code here
if(head1 == NULL)
{
return head2;
}
if(head2 == NULL)
{
return head1;
}
//反转链表
head1 = reverseList(head1);
head2 = reverseList(head2);
//res应为局部变量 如果使用malloc分配 会存在内存泄漏 每次调用函数导致外部无法释放头节点
//res为哨兵节点
struct ListNode res;
struct ListNode *phead = &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 = temp % 10;
phead->next = malloc(sizeof(struct ListNode));
if(phead->next == NULL)
{
return NULL;
}
phead = phead->next;
//保存
phead->val = temp;
//移动下一个
if(head1 != NULL){
head1 = head1->next;
}
if (head2 != NULL) {
head2 = head2->next;
}
}
return reverseList(res.next);
}