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

链表相加(二)

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

/**
 * struct ListNode {
 *  int val;
 *  struct ListNode *next;
 * };
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 *
 * @param head1 ListNode类
 * @param head2 ListNode类
 * @return ListNode类
 */
struct ListNode* reverseList(struct ListNode* head) {
    if (head == NULL || head->next == NULL)
        return head;
    struct ListNode* new_head = NULL;
    while (head != NULL) {
        struct ListNode* next = head->next;
        head->next = new_head;
        new_head = head;
        head = next;
    }
    return new_head;
}

struct ListNode* addInList(struct ListNode* head1, struct ListNode* head2) {
    // write code here
    if (head1 == NULL && head2 == NULL)
        return NULL;
    struct ListNode* new_head1 = reverseList(head1);
    struct ListNode* new_head2 = reverseList(head2);
    struct ListNode* dummy = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* res = dummy;
    int carry = 0; // 进位
    while (new_head1 != NULL || new_head2 != NULL) {
        int sum = carry;
        if (new_head1 != NULL) {
            sum += new_head1->val;
            new_head1 = new_head1->next;
        }
        if (new_head2 != NULL) {
            sum += new_head2->val;
            new_head2 = new_head2->next;
        }
        carry = sum / 10;
        struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
        node->val = sum % 10;
        node->next = NULL;
        res->next = node;
        res = res->next;
    }
    if (carry > 0) {
        struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
        node->val = carry;
        node->next = NULL;
        res->next = node;
    }
    struct ListNode* new_head3 = reverseList(dummy->next);
    return new_head3;
}

全部评论

相关推荐

09-12 11:55
已编辑
湖南工商大学 Java
那一天的Java_J...:这种一堆问题的,别去
点赞 评论 收藏
分享
LXXXXd:有点杂,想搞自动化的话没必要把法律的经历写上去
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务