LeetCode——2. Add Two Numbers

来源:互联网 发布:火车票买票软件 编辑:程序博客网 时间:2024/05/01 20:59

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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)

Output: 7 -> 0 -> 8

结构体中的每个成员都要初始化,不然会报Runtime Error

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; */struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {        int c = 0 ;    struct ListNode *head =  (struct ListNode*)malloc(sizeof(struct ListNode));    struct ListNode *sum = head;    head->val = 0 ;    head->next = NULL ;        while( l1!=NULL && l2!=NULL )    {        struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));        node->val =l1->val+ l2->val +c ;        node->next= NULL ;                if( node->val >= 10 )        {            node->val = node->val%10 ;            c = 1 ;        }        else        {            c = 0 ;        }                sum->next = node;        sum = node ;        l1 = l1->next ;        l2 = l2->next ;    }        //l2链表已经结束    while(l1!= NULL)    {        struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));        node->val = l1->val+c ;        node->next=NULL ;        if( node->val >= 10)        {            node->val = node->val%10 ;            c = 1 ;        }        else        {            c = 0 ;        }        sum->next = node;        sum = node ;        l1 = l1->next;    }        //l1链表已经结束    while(l2 != NULL)    {        struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));        node->val = l2->val +c ;        node->next=NULL ;        if(node->val >= 10)        {            node->val = node->val%10;            c = 1;        }         else        {            c = 0 ;        }        sum->next = node;        sum = node ;        l2 = l2->next ;    }        if(c == 1)    {        struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));        node->val = 1 ;        node->next = NULL ;        sum->next = node;    }    return head->next ;}


0 0
原创粉丝点击