题目
给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照逆序的方式存储的,并且每个节点只能存储一位数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
提示
示例 1:
输入:l1 = [2,4,3], l2 = [5,6,4]
输出:[7,0,8]
解释: 342 + 465 = 807.
示例 2:
输入:l1 = [0], l2 = [0]
输出:[0]
示例 3:
输入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
输出:[8,9,9,9,0,0,0,1]
代码
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
// Notice! when init the point the * is before the value
// struct ListNode *head = NULL, *tail = NULL;
struct ListNode* head = NULL;
struct ListNode* tail = NULL;
int carry = 0;
while(l1 || l2) {
int num1 = l1 ? l1->val : 0;
int num2 = l2 ? l2->val : 0;
int sum = num1 + num2 + carry;
if(!head) {
// init the head point to keep the point of first node
head = tail = (struct ListNode*)malloc(sizeof(struct ListNode));
tail->val = sum % 10;
tail->next = NULL;
} else {
// init the next node
tail->next = (struct ListNode*)malloc(sizeof(struct ListNode));
tail->next->val = sum % 10;
tail->next->next = NULL;
// move the point
tail = tail->next;
}
carry = sum / 10;
if (l1) {
l1 = l1->next;
}
if (l2) {
l2 = l2->next;
}
}
// if the carry not equal to zero, we need another node to store it.
if (carry > 0) {
tail->next = (struct ListNode*)malloc(sizeof(struct ListNode));
tail->next->val = carry;
tail->next->next = NULL;
}
return head;
}
struct ListNode* createLinkedList(int arr[], int n) {
struct ListNode* head = NULL;
struct ListNode* tail = NULL;
for (int i = 0; i < n; i++) {
if (!head) {
head = tail = (struct ListNode*)malloc(sizeof(struct ListNode));
tail->val = arr[i];
tail->next = NULL;
} else {
tail->next = (struct ListNode*)malloc(sizeof(struct ListNode));
tail->next->val = arr[i];
tail->next->next = NULL;
tail = tail->next;
}
}
return head;
}
int main() {
struct ListNode* l1 = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* l2 = (struct ListNode*)malloc(sizeof(struct ListNode));
// init the list
int arr[] = {2,4,3};
int arr2[] = {5,6,4};
l1 = createLinkedList(arr, 3);
l2 = createLinkedList(arr2, 3);
struct ListNode* res = addTwoNumbers(l1, l2);
// print the list
while(res) {
printf("%d\n", res->val);
res = res->next;
}
return 0;
}
链表问题大多考察链表操作,所以没有分析
这个题注意,给出的链表和最后的结果都是逆序,直接向后进位即可