题解 | #两个链表生成相加链表#

两个链表生成相加链表

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

反转两个链表,然后相加

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

/**
 * 
 * @param head1 ListNode类 
 * @param head2 ListNode类 
 * @return ListNode类
 */

struct ListNode* reverse(struct ListNode* head)
{
    if (head == NULL || head->next == NULL)
    {
        return head;
    }
    struct ListNode* new_head = NULL;
    struct ListNode* cur = NULL;
    while (head)
    {
        cur = head;
        head = head->next;
        cur->next = new_head;
        new_head = cur;
        
    }
    return new_head;
}


struct ListNode* addInList(struct ListNode* head1, struct ListNode* head2) {
    // write code here
    int carry = 0;
    struct ListNode* head = NULL;
    struct ListNode* p = NULL;
    head1 = reverse(head1); // 7 3 9
    head2 = reverse(head2); // 3 6
    while (head1 || head2 || carry != 0)
    {
        int s = 0;
        if (head1)
        {
            s += head1->val;
            head1 = head1->next;
        }
        if (head2)
        {
            s += head2->val;
            head2 = head2->next;
        }
        p = (struct ListNode*)malloc(sizeof(struct ListNode));
        s += carry;
        p->val = (s % 10);
        carry = s / 10;
        p->next = head;
        head = p;
    }

    return head;
}
全部评论

相关推荐

点赞 评论 收藏
分享
小浪_Coding:找硬件测试,也可兼顾软测欧, 简历还可以的 ,注意排版,项目写的有条理一点, 然后个人技能多加点, 润色好简历之后就开始沟通海投了,深圳,东莞这边做硬件相关的公司还不少, 医疗类,仪器类的都可以尝试
点赞 评论 收藏
分享
06-12 16:23
已编辑
小米_软件开发(准入职员工)
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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