代码美观学习
力扣第二题,原文链接。
自己写完后与官方解题代码对比,感觉官方的很美观,故此记录。
struct ListNode {
int val;
struct ListNode *next;
};
//下面是官方的。*整洁干净、朴实易读
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode *head = NULL, *tail = NULL;
int carry = 0;
while (l1 || l2) {
int n1 = l1 ? l1->val : 0;
int n2 = l2 ? l2->val : 0;
int sum = n1 + n2 + carry;
if (!head) {
head = tail = malloc(sizeof(struct ListNode));
tail->val = sum % 10;
tail->next = NULL;
} else {
tail->next = malloc(sizeof(struct ListNode));
tail->next->val = sum % 10;
tail = tail->next;
tail->next = NULL;
}
carry = sum / 10;
if (l1) {
l1 = l1->next;
}
if (l2) {
l2 = l2->next;
}
}
if (carry > 0) {
tail->next = malloc(sizeof(struct ListNode));
tail->next->val = carry;
tail->next->next = NULL;
}
return head;
}
作者:LeetCode-Solution
链接:https://leetcode.cn/problems/add-two-numbers/solution/liang-shu-xiang-jia-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
//下面这里是我写的,感觉直接差了一个档次。
//所以鼓励自己不断学习优秀代码及其书写风格
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
struct ListNode *l3;
l3 = malloc(sizeof(struct ListNode));
l3->next = NULL;
int jinwei_flag = 0;
l3->val = (l1->val + l2->val) % 10;
if (l1->val + l2->val >= 10)
{
jinwei_flag = 1;
}
struct ListNode *node_x = l1->next;
struct ListNode *node_y = l2->next;
struct ListNode *l3_tail = l3;
while (node_x != NULL || node_y != NULL)
{
struct ListNode *node_z;
node_z = malloc(sizeof(struct ListNode));
node_z->next = NULL;
int data_x = 0;
int data_y = 0;
if (node_x != NULL)
{
data_x = node_x->val;
}
if (node_y != NULL)
{
data_y = node_y->val;
}
node_z->val = (jinwei_flag + data_x + data_y) % 10;
if (jinwei_flag + data_x + data_y >= 10)
{
jinwei_flag = 1;
}
else
{
jinwei_flag = 0;
}
l3_tail->next = node_z;
l3_tail = node_z;
if (node_x != NULL)
{
node_x = node_x->next;
}
if (node_y != NULL)
{
node_y = node_y->next;
}
}
if (jinwei_flag == 1)
{
struct ListNode *node_z;
node_z = malloc(sizeof(struct ListNode));
node_z->next = NULL;
node_z->val = 1;
l3_tail->next = node_z;
l3_tail = node_z;
}
return l3;
}