题解 | #链表相加(二)#

链表相加(二)

https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 *
 * C语言声明定义全局变量请加上static,防止重复定义
 *
 * C语言声明定义全局变量请加上static,防止重复定义
 */

/**
 * 
 * @param head1 ListNode类 
 * @param head2 ListNode类 
 * @return ListNode类
 */
struct ListNode* ReverseList(struct ListNode* pHead){
    struct ListNode* res = NULL;
    struct ListNode* cur = pHead;
    while(cur){
        struct ListNode* temp = cur->next;
        cur->next = res;
        res = cur;
        cur = temp;
    }
    
    return res;
}

struct ListNode* addInList(struct ListNode* head1, struct ListNode* head2 ) {
    // write code here
    struct ListNode* l1 = ReverseList(head1);
    struct ListNode* l2 = ReverseList(head2);
    struct ListNode* res = NULL;
    int cnt = 0;
    
    while(l1 || l2){
        int x1 = l1 == NULL ? 0 : l1->val;
        int x2 = l2 == NULL ? 0 : l2->val;
        
        l1 = l1 == NULL ? NULL : l1->next;
        l2 = l2 == NULL ? NULL : l2->next;
      
        int sum = x1 + x2 + cnt;
        cnt = sum/10;
        
        struct ListNode* temp = (struct ListNode*)malloc(sizeof(struct ListNode));
        temp->val = sum%10;
        
        temp->next = res;
        res = temp;
        
    }
    
    if(cnt > 0){
        struct ListNode* temp = (struct ListNode*)malloc(sizeof(struct ListNode));
        temp->val = cnt;
        temp->next = res;
        res = temp;
    }
    
    return res;
}

全部评论

相关推荐

MingoTree:看不出你你的技术栈,想找什么工作,然后课设项目别写上去了,自我评价删了,前后端你想好你要干啥,这种简历投上去秒挂的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务