前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【LeetCode】2. Add Two Numbers

【LeetCode】2. Add Two Numbers

作者头像
韩旭051
发布2019-11-08 16:33:14
2640
发布2019-11-08 16:33:14
举报
文章被收录于专栏:刷题笔记刷题笔记

版权声明:本文为博主原创文章,遵循 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;
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-26 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 我太难了,感觉自己C语言语法上咋都有这么多问题呢~~~~各种指针异常,以前刷pat都没遇到过。现在问题全都暴露出来了
    • 先研究别人的优秀的代码,快速的过一遍吧,回过头来再看。反正数据结构啥的我都还没有学呢~~~
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档