Add Two Numbers

来源:互联网 发布:mac怎么装office软件 编辑:程序博客网 时间:2024/06/16 03:11

You are given two linked lists representing two non-negative numbers. 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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

这道题主要容易忽略的几点在:
1 , 链表 L1 和 L2 不一定是一样长的 ,设计的程序必须考虑到.
2, 这道题的问题主要不光要考虑到时间复杂度(感觉都能过),还要注意要空间复杂度(不要浪费空间).
其他应该不是问题,我的代码如下:
(老实说这个解法并不太好,只是为了完成任务,如果有更好的希望能告知我)

struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {      int   n,coun =0;       struct ListNode *ptr ,*head ;    head =ptr= malloc(sizeof(struct ListNode));      for( ; ;)      {            if( l1 !=NULL)                {  n = l1->val;                    l1 =l1->next;                }else                {                    n =0;                }             if( l2 != NULL)            {                    n += l2->val;                    l2 = l2->next;            }                    n += coun;                ptr->next = malloc(sizeof(struct ListNode));                ptr = ptr->next;                       ptr->val = (n)%10;                    coun =n/10;                   if(l1==NULL &&l2==NULL&&coun==0)                       {ptr->next =NULL;                        break;                       }        }                    ptr=head->next;                     free(head);                     return(ptr);                   }
0 0