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

链表相加(二)

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) {
    // write code here
    if (head == NULL || head->next == NULL)
        return head;
    struct ListNode* pre = NULL;
    struct ListNode* mid = head;
    struct ListNode* next = NULL;
    while (mid != NULL) {
        next = mid->next;
        mid->next = pre;
        pre = mid;
        mid = next;
    }
    return pre;
}
struct ListNode* addInList(struct ListNode* head1, struct ListNode* head2 ) {
    // write code here
    if (head1 == NULL && head2 != NULL) {
        return head2;
    }
    if (head2 == NULL && head1 != NULL) {
        return head1;
    }
    head1 = ReverseList(head1);
    head2 = ReverseList(head2);
    int flag = 0;
    struct ListNode* temp = (struct ListNode*) malloc(sizeof(struct ListNode));
    temp->next = NULL;
    struct ListNode* pre = temp;
    int value = 0;
    int val1 = 0;
    int val2 = 0;
    while (head2 != NULL || head1 != NULL||flag==1) {
        val1 = head1 == NULL ? 0 : head1->val;
        val2 = head2 == NULL ? 0 : head2->val;
        value = val1 + val2 + flag;
        struct ListNode* node = (struct ListNode*) malloc(sizeof(struct ListNode));
        node->next = NULL;
        if (value >= 10) {
            flag = 1;
            value = value % 10;
            node->val = value;
            pre->next = node;
        } else {
            flag = 0;
            node->val = value;
            pre->next = node;
        }
        pre = pre->next;
        if (head1 != NULL) {
            head1 = head1->next;
        }
        if (head2 != NULL) {
            head2 = head2->next;
        }
    }
    struct ListNode* dummy = temp->next;
    free(temp);
    return ReverseList(dummy);
}

全部评论

相关推荐

07-23 18:18
门头沟学院 Java
点赞 评论 收藏
分享
Vincent777...:实习经历可以考虑放上去,对于软件使用方面可以细化一些,比如调整为:熟悉基于LSDYNA的瞬态动力学仿真分析,熟悉基于WORKBENCH的结构拓扑优化
我的简历长这样
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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