算法题练习(一)

独兜曲

关注

阅读 62

2022-04-05

两数相加

在这里插入图片描述

/**
 *结构体信息
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
    int dj = 0;  //进位
    struct ListNode *p = l1;
    struct ListNode *q = l2;
    struct ListNode *new,*old;
    new = old = (struct ListNode*)malloc(sizeof(struct ListNode));
    while(p && q){
        struct ListNode *new_Node = (struct ListNode*)malloc(sizeof(struct ListNode));
        new_Node->val = (q->val + p->val+dj)%10;
        dj = (q->val + p->val+dj)/10;
        new->next = new_Node;
        new = new_Node;
        p = p->next;
        q = q->next;
    }
    while(p){
        struct ListNode *new_Node = (struct ListNode*)malloc(sizeof(struct ListNode));
        new_Node->val = ( p->val+dj)%10;
        dj = (dj + p->val)/10;
        new->next = new_Node;
        new = new_Node;
        p = p->next;
    }
    while(q){
        struct ListNode *new_Node = (struct ListNode*)malloc(sizeof(struct ListNode));
        new_Node->val = (q->val+dj)%10;
        dj = (q->val + dj)/10;
        new->next = new_Node;
        new = new_Node;
        q = q->next;
    }
    if(dj){
        struct ListNode *new_Node = (struct ListNode*)malloc(sizeof(struct ListNode));
        new_Node->val = dj;
        new->next = new_Node;
        new = new_Node;
    }
    new->next = NULL;
    return old->next;
}

在这里插入图片描述

精彩评论(0)

0 0 举报