/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
// 初始化返回链表的头结点和尾结点
struct ListNode * head = NULL;
struct ListNode * tail = NULL;
// 初始化carry,即进位值
int carry = 0;
int sum;
// 循环遍历这两个链表,只要有其中一个的头指针不为NUll,就继续遍历
while (l1 || l2) {
// 为结构体分配内存
struct ListNode * tempNode = (struct ListNode *) malloc(sizeof(struct ListNode));
tempNode -> next = NULL;
// 获取当前头结点存储的值,如果当前结点为NULL,则说明链表已经遍历完了,将其值置为0
int n1 = l1 ? l1 -> val : 0;
int n2 = l2 ? l2 -> val : 0;
// 对其求和
sum = n1 + n2 + carry;
//如果头指针不存在,就对其赋值
if (!head) {
tempNode -> val = sum % 10;
head = tail = tempNode;
} else {
// 如果头指针存在,则对尾指针赋值(即移动尾指针)
tempNode -> val = sum % 10;
tail -> next = tempNode;
tail = tempNode;
}
// 更新carry
carry = sum / 10;
// 移动l1和l2
if (l1) {
l1 = l1 -> next;
}
if (l2) {
l2 = l2 -> next;
}
}
// 如果进位值大于0,则再分配一个结点存储该值,添加结点,并移动尾指针
if (carry > 0) {
struct ListNode * tempNode = (struct ListNode *) malloc(sizeof(struct ListNode));
tempNode -> val = carry;
tempNode -> next = NULL;
tail -> next = tempNode;
tail = tempNode;
}
// 返回结果链表的头指针
return head;
}执行用时:8 ms, 在所有 C 提交中击败了99.29%的用户
内存消耗:7.7 MB, 在所有 C 提交中击败了14.46%的用户