leetcode 2 두 수 더하기 (C 언어 버 전)

3027 단어 leetcode


#include 

#include

 

struct ListNode {

   
int val;

   
struct ListNode *next;

};

 

struct ListNode* addTwoNumbers(struct
ListNode* l1, struct ListNode* l2) {

   
struct ListNode *t,*p,*q,*l;

   
t=(struct ListNode *)malloc(sizeof(struct ListNode));

   
t->val=0;

   
t->next=NULL;

   
p=l1;

   
q=l2;  //p&q  l1&l2   ,   malloc    ->val,->next

   
l=t;  //l   t    

   
while(p!=NULL&&q!=NULL)

    {

       
struct ListNode*node=(struct ListNode*)malloc(sizeof(struct ListNode));

       
node->val=0;

        node->next=NULL;

       
t->next=node;

       
t->val+=(p->val+q->val);

       
if(t->val>=10)

       
{

           
t->val-=10;

           
node->val=1;

       
}

       
p=p->next;

       
q=q->next;

       
if(p==NULL&&q==NULL&&node->val == 0)  //      

           
t->next=NULL;

       
t=t->next;

    }

   
while(p!=NULL)

    {

       
struct ListNode* node = (struct ListNode*)malloc(sizeof(struct
ListNode));

       
node->val=0;

       
node->next=NULL;

       
t->next=node;

       
t->val+=p->val;

        if(t->val>=10)

       
{

           
t->val-=10;

           
node->val=1;

       
}

       
p=p->next;

       
if(p==NULL&&node->val == 0)

           
t->next=NULL;

       
t=t->next;

    }

   
while(q!=NULL)

    {

       
struct ListNode* node = (struct ListNode*)malloc(sizeof(struct
ListNode));

       
node->val=0;

       
node->next=NULL;

       
t->next=node;

       
t->val+=q->val;

       
if(t->val>=10)

       
{

           
t->val-=10;

           
node->val=1;

       
}

       
q=q->next;

       
if(q==NULL&&node->val == 0)

           
t->next=NULL;

       
t=t->next;

    }

   
return l;

}

int main()

{

   
struct ListNode *l1,*l2,*l,*p1,*p2,*t;

   
l1=(struct ListNode*)malloc(sizeof(struct ListNode*));

   
l2=(struct ListNode*)malloc(sizeof(struct ListNode*));

   
l1->val=0;

   
l2->val=0;

   
l1->next=NULL;

   
l2->next=NULL;

   
p1=l1;

   
p2=l2;  //p1&p2            ,  malloc

   
do

    {

       
scanf("%d",&l1->val);

       
l=(struct ListNode*)malloc(sizeof(struct ListNode*));  //  malloc    ,         ,      

       
l->val=0;

       
l->next=NULL;

       
l1->next=l;

       
l1=l1->next;

   
}while(getchar()!='
'); do { scanf("%d",&l2->val); l=(struct ListNode*)malloc(sizeof(struct ListNode*)); l->val=0; l->next=NULL; l2->next=l; l2=l2->next; }while(getchar()!='
'); // getchar t=addTwoNumbers(p1,p2); // while(t!=NULL) // t->next!=NULL { printf("%d",t->val); t=t->next; } return 0; }

좋은 웹페이지 즐겨찾기