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

链表相加(二)

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){
    struct ListNode* dummy = (struct ListNode*)malloc(sizeof(struct ListNode));
    dummy->next = NULL;
    struct ListNode* new_lis = dummy;
    struct ListNode* p = head;
    struct ListNode* q;
    q = p->next;
    while(p!=NULL){
        p->next = dummy->next;
        dummy->next = p;
        p = q;
        q = p->next;
    }

    return dummy->next;
}

struct ListNode* addInList(struct ListNode* head1, struct ListNode* head2 ) {
    // write code here
    //翻转p1,p2
    struct ListNode* p1 = reverseList(head1);
    struct ListNode* p2 = reverseList(head2);
    struct ListNode* resul = (struct ListNode*)malloc(sizeof(struct ListNode));
    resul->next = NULL;
    int temp = 0;

    while(p1!=NULL || p2!=NULL){
        int value = temp;
        if(p1!=NULL){
            value+=p1->val;
            p1 = p1->next;
        }
        if(p2!=NULL){
            value+=p2->val;
            p2 = p2->next;
        }
        //新建结点并插入
        struct ListNode *temp_node = (struct ListNode*)malloc(sizeof(struct ListNode));
        temp_node->val = value%10;
        temp_node->next = resul->next;
        resul->next = temp_node;
        temp = value/10;
    }

        //可能最高位多出来的进位
    if(temp == 1){
        struct ListNode *temp_node = (struct ListNode*)malloc(sizeof(struct ListNode));
        temp_node->val = temp;
        temp_node->next = resul->next;
        resul->next = temp_node;
    }
    
    return resul->next;
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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