【LeetCode】2. Add Two Numbers

2019-11-08 16:33:14 浏览数 (1)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

本文链接:https://blog.csdn.net/shiliang97/article/details/101436465

题目描述

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

代码语言:javascript复制
Input: (2 -> 4 -> 3)   (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342   465 = 807.

我太难了,感觉自己C语言语法上咋都有这么多问题呢~~~~各种指针异常,以前刷pat都没遇到过。现在问题全都暴露出来了

先研究别人的优秀的代码,快速的过一遍吧,回过头来再看。反正数据结构啥的我都还没有学呢~~~

代码语言:javascript复制
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
    int flag = 0, nodeSum = 0, freeflag = 0;
    struct ListNode *ret,*now,*high,*freeBegin,*freeEnd;
    for(ret = l1, now = l1, high = l2, freeBegin = l2;l1  || l2  || flag ;) {  
        if (l1 == NULL && l2 == NULL) {
              now->next = high;
              now = now->next;
              freeBegin = now->next;
        }
        nodeSum = ( l1  ? l1->val : 0 )   (l2 ? l2->val : 0)   flag;  
        now->val = nodeSum % 10;    
        flag =  nodeSum / 10; 
        l1 ? l1 = (l1->next ? l1->next : NULL) : NULL;
        if(l1 == NULL && 0 == freeflag && l2) {
            freeEnd = l2;
            freeflag = 1;
        }
        l2 ? l2 = (l2->next ? l2->next : NULL) : NULL;
        now->next = ( l1 ? l1 : (l2 ?  l2 : NULL) );
        now->next ? now = now->next : NULL;
    }
    l2 = freeBegin;
    freeEnd->next = NULL;
    return ret;
}

0 人点赞