zoukankan      html  css  js  c++  java
  • [leetcode]2两数相加

    题目将数据以链表方式给出,并且很贴心的设计成了倒序,也就是说我们读取数字的时候正好是按照从地位到高位读取的,因此每次读取是就进行一次计算即可。关于相加时候需要注意的进位问题这里就不多说了。

     1 struct ListNode *ans = (struct ListNode *)malloc(sizeof(struct ListNode));
     2     struct ListNode *now = NULL;
     3     struct ListNode *next = NULL;
     4     int num1 = 0, num2 = 0, sum = 0, flag = 0;
     5     now = ans;
     6     //now->next = NULL;
     7     while (l1 != NULL || l2 != NULL || flag == 1)
     8     {
     9         num1 = (l1 != NULL) ? l1->val : 0;
    10         num2 = (l2 != NULL) ? l2->val : 0;
    11         sum = num1 + num2+flag;
    12         flag=sum/10;
    13         sum=sum%10;
    14         
    15         /*next = (struct ListNode *)malloc(sizeof(struct ListNode));
    16         next->val = sum;
    17         now->next = next;
    18         next->next = NULL;
    19         now = next;*/
    20         
    21         next=(struct ListNode*)malloc(sizeof(struct ListNode));
    22         next->val=sum;
    23 
    24         now->next=next;
    25         next->next=NULL;//这句话特别重要,如果不在末尾设置空指针的话,会报错。
    26         now=next;
    27         
    28         l1 = (l1 != NULL) ? l1->next : l1;
    29         l2 = (l2 != NULL) ? l2->next : l2;
    30     } 
    31     
    32     return ans->next;
  • 相关阅读:
    NTP时间同步
    《暗时间》
    寻找字典公共键
    maven pom.xml的execution报错
    maven安装scala插件
    html 和xml
    sparkstreaming+kafka
    zookeeper错误Error contacting service. It is probably not running.
    eclipse开发hive2程序
    eclipse开发hbase程序
  • 原文地址:https://www.cnblogs.com/trickofjoker/p/10537850.html
Copyright © 2011-2022 走看看