Chinaunix首页 | 论坛 | 博客
  • 博客访问: 359406
  • 博文数量: 60
  • 博客积分: 15
  • 博客等级: 民兵
  • 技术积分: 1138
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-20 16:18
个人简介

最多140个字

文章分类

全部博文(60)

文章存档

2016年(1)

2015年(34)

2014年(25)

分类: C/C++

2015-08-12 15:21:50

/>
  1. /**
  2.  * Definition for singly-linked list.
  3.  * struct ListNode {
  4.  * int val;
  5.  * struct ListNode *next;
  6.  * };
  7.  */
  8.  
  9. int lenstr(struct ListNode *h,struct ListNode **t)
  10. {
  11.     struct ListNode *tmp=h;
  12.     int len=0;
  13.     while(tmp->next!=NULL)
  14.     {
  15.         tmp=tmp->next;
  16.         len++;
  17.     }
  18.     *t=tmp;
  19.     return len;
  20. }
  21. struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
  22.     if(l1==NULL)
  23.         return l2;
  24.     else if(l2==NULL)
  25.         return l1;
  26.     else
  27.     {
  28.         struct ListNode *tail=NULL;
  29.         struct ListNode *t1=NULL;
  30.         struct ListNode *t2=NULL;
  31.         int len1=lenstr(l1,&t1);
  32.         int len2=lenstr(l2,&t2);
  33.         struct ListNode *i1=NULL;
  34.         struct ListNode *i2=NULL;
  35.         if(len1>len2)
  36.         {
  37.             i1=l1;
  38.             tail=t1;
  39.             i2=l2;
  40.         }
  41.         else
  42.         {
  43.             i1=l2;
  44.             tail=t2;
  45.             i2=l1;
  46.         }
  47.         int flag=0;
  48.       
  49.         struct ListNode *head=i1;
  50.         while(i1!=NULL)
  51.         {
  52.             if(i2!=NULL)
  53.             {
  54.                 i1->val=i1->val+i2->val+flag;
  55.                 flag=i1->val/10;
  56.                 i1->val=i1->val%10;
  57.                 i1=i1->next;;
  58.                 i2=i2->next;
  59.             }
  60.             else
  61.             {
  62.                 i1->val=i1->val+flag;
  63.                 flag=i1->val/10;
  64.                 i1->val=i1->val%10;
  65.                 i1=i1->next;
  66.                 if(flag==0)
  67.                     break;
  68.             }
  69.         }
  70.         if(flag)
  71.         {
  72.                 struct ListNode *tmp=malloc(sizeof(struct ListNode));
  73.                 tmp->val=flag;
  74.                 tmp->next=NULL;
  75.                 tail->next=tmp;
  76.         }
  77.         return head;
  78.     }
  79.   
  80.     
  81. }


阅读(2572) | 评论(0) | 转发(0) |
0

上一篇:git bisect

下一篇:Merge k Sorted Lists

给主人留下些什么吧!~~