leetcode链表专题
Posted BHY_
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode链表专题相关的知识,希望对你有一定的参考价值。
本文持续更新leetcode上适用于C语言链表相关题目解法:
题目:2. 两数相加
链接:https://leetcode-cn.com/problems/add-two-numbers/
解析:遵循加法运算法则
答案:
/**
* Definition for singly-linked list.
* struct ListNode
* int val;
* struct ListNode *next;
* ;
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2)
if (l1 == NULL)
return l2;
if (l2 == NULL)
return l1;
struct ListNode* res = (struct ListNode*)malloc(sizeof(struct ListNode));
res->next = NULL;
struct ListNode* head = res;
int c = 0; // 进位
while (l1 != NULL && l2 != NULL)
head->val = (l1->val + l2->val + c) % 10;
c = (l1->val + l2->val + c) / 10;
l1 = l1->next;
l2 = l2->next;
if (l1 != NULL && l2 != NULL)
struct ListNode* tmp = (struct ListNode*)malloc(sizeof(struct ListNode));
head->next = tmp;
head = head->next;
head->next = NULL;
while (l1 != NULL)
struct ListNode* tmp = (struct ListNode*)malloc(sizeof(struct ListNode));
head->next = tmp;
head = head->next;
head->next = NULL;
head->val = (l1->val + c) % 10;
c = (l1->val + c) / 10;
l1 = l1->next;
while (l2 != NULL)
struct ListNode* tmp = (struct ListNode*)malloc(sizeof(struct ListNode));
head->next = tmp;
head = head->next;
head->next = NULL;
head->val = (l2->val + c) % 10;
c = (l2->val + c) / 10;
l2 = l2->next;
if (c != 0)
struct ListNode* tmp = (struct ListNode*)malloc(sizeof(struct ListNode));
head->next = tmp;
head = head->next;
head->next = NULL;
head->val = c;
return res;
结果:
执行结果:通过
执行用时 :12 ms, 在所有 C 提交中击败了95.85%的用户
内存消耗 :7.4 MB, 在所有 C 提交中击败了100.00%的用户
以上是关于leetcode链表专题的主要内容,如果未能解决你的问题,请参考以下文章