/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* @author Senky
* @date 2023.04.19
* @par url https://www.nowcoder.com/creation/manager/content/584337070?type=column&status=-1
* @brief
* (1)结点指针可能为NULL,不能用结点指针直接访问结点的数据域&指针域(head->val,head->next在head为空是都是非法访问)
因此得先if()判断一下;
* (2)先将两个链表翻转,原来的'头'就是现在的'尾';
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
struct ListNode* ReverseList(struct ListNode* pHead ) {
// write code here
struct ListNode* prev = NULL;
struct ListNode* curr = pHead;
struct ListNode* next;
//退出循环后curr指向NULL
while(curr != NULL)
{
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
struct ListNode* addInList(struct ListNode* head1, struct ListNode* head2 ) {
// write code here
struct ListNode* p = NULL;
head1 = ReverseList(head1);
head2 = ReverseList(head2);
int cf = 0;
int num1 = 0;
int num2 = 0;
while(head1 || head2)
{
num1 = (head1)?(head1->val):(0);
num2 = (head2)?(head2->val):(0);
struct ListNode* Node = (struct ListNode*)malloc(sizeof(struct ListNode));
Node->val = ( num1 + num2 + cf )%10;
Node->next = p;
p = Node;
cf = ( num1 + num2 + cf >= 10)?(1):(0);
if(head1) head1 = head1->next;
if(head2) head2 = head2->next;
}
return p;
}
Algorithm:
现将链表翻转(BM1写过),头成了"尾",尾就成了"头","头"对齐相加即可;

京公网安备 11010502036488号