1.力扣C源码
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
struct ListNode* p = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* q = p;
int carry = 0;
while (l1 || l2) {
struct ListNode* r = (struct ListNode*)malloc(sizeof(struct ListNode));
int val1 = l1 ? l1->val : 0;
int val2 = l2 ? l2->val : 0;
int val = val1 + val2 + carry;
if (val >= 10) {
val -= 10;
carry = 1;
}
else {
carry = 0;
}
r->val = val;
q->next = r;
q = q->next;
l1 = l1 ? l1->next : l1;
l2 = l2 ? l2->next : l2;
}
if (carry == 1) {
struct ListNode* r = (struct ListNode*)malloc(sizeof(struct ListNode));
r->val = 1;
q->next = r;
q = q->next;
}
q->next = NULL;
return p->next;
}
2.题解
模拟两数相加的过程。设置一个辅助位carry记录进位(0 or 1)。加法的过程示意图如下:
- 1.考虑数字相加的进位问题。用carry来记录(取值为0或者1)
- 2.最高位进位问题,即在当前链表后再加一个节点,值为1
- 3.如何处理链表的头节点问题?设置两个节点p,q,p作为头节点(没有实际意义),q往后递增,作为指向每次添加到链表末尾的节点的指针,结束后返回p->next即可
3.VS可运行源码
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<vector>
#include<limits>
#include<algorithm>
#pragma warning(disable:4996)
using namespace std;
struct ListNode {
int val;
struct ListNode *next;
};
int n3;
ListNode* List_TailInsert3()
{
ListNode* head = (ListNode*)malloc(sizeof(ListNode));
ListNode* rear = head;
printf("输入链表数据:");
int num;
for (int i = 0; i < n3; i++) {
scanf("%d", &num);
ListNode* p = (ListNode*)malloc(sizeof(ListNode));
p->val = num;
rear->next = p;
rear = p;
}
rear->next = NULL;
return head;
}
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
ListNode* head1 = l1->next;
ListNode* head2 = l2->next;
ListNode* p = (ListNode*)malloc(sizeof(ListNode));
ListNode* q = p;
int carry = 0;
while (head1 || head2) {
ListNode* r = (ListNode*)malloc(sizeof(ListNode));
int val1 = head1 ? head1->val : 0;
int val2 = head2 ? head2->val : 0;
int val3 = val1 + val2 + carry;
if (val3 >= 10) {
val3 -= 10;
carry = 1;
}
else {
carry = 0;
}
r->val = val3;
q->next = r;
q = q->next;
head1 = head1 ? head1->next : head1;
head2 = head2 ? head2->next : head2;
}
if (carry == 1) {
ListNode* r = (ListNode*)malloc(sizeof(ListNode));
r->val = 1;
q->next = r;
q = q->next;
}
q->next = NULL;
return p->next;
}
int main()
{
printf("输入第一个链表的长度:");
scanf("%d", &n3);
ListNode* head1 = List_TailInsert3();
printf("输入第二个链表的长度:");
scanf("%d", &n3);
ListNode* head2 = List_TailInsert3();
ListNode* head = addTwoNumbers(head1, head2);
ListNode* p = head;
while (p) {
printf("%d", p->val);
p = p->next;
}
system("pause");
return 0;
}
4.特别注意
最后这行代码一定不要忘
q->next = NULL;
|