《leetCode》:add two num

《leetCode》:add two num

题目描述如下

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

意思就是:用两个链表表示的两个非负整数进行相加运算。

实现代码如下:

由于是在线编程,因此也就没有写测试代码。

  • 当两个链表一长一短的时候,还需要将最后的进位与长链表剩余的结点进行相加运算。最后也要看是否最高位产生了进位,若产生了进位,则需要新建一个节点来表示最高位。
  • 当两个链表一样长的时候,还需要考虑是否最高位产生了进位。若产生了最高位,则需要新建一个节点来表示最高位。
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
 int list_len(struct ListNode* list){
     if(list==NULL){
         return 0;
     }
     int len=1;
     while(list->next!=NULL){
         len++;
         list=list->next;

     }
     return len;

 }
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    if(l1==NULL){//有效性检查
        return l2;
    }
    if(l2==NULL){
        return l1;
    }
    //求出两个链表的长度
    int len1=list_len(l1);
    int len2=list_len(l2);
    //长链表代表大的数,短链表代表小的数
    struct ListNode* highNum=l1;
    struct ListNode* lowNum=l2;
    int highLen=len1;
    int lowLen=len2;
    if(len1<len2){
        highNum=l2;
        lowNum=l1;
        highLen=len2;
        lowLen=len1;
    }
    int ci=0;//表示进位
    struct ListNode* cur1=highNum;
    struct ListNode* cur2=lowNum;
    struct ListNode* pre=NULL;
    while(lowLen>0){
        int temp=cur1->val+cur2->val+ci;
        cur1->val=temp%10;
        ci=temp/10;
        pre=cur1;
        cur1=cur1->next;
        cur2=cur2->next;
        lowLen--;
        highLen--;

    }
    //将最后一个进位与长链表中剩余的结点相加
    if(highLen>0&&ci>0){

        while(highLen>0){
            int temp=cur1->val+ci;
            cur1->val=temp%10;
            ci=temp/10;
            pre=cur1;
            cur1=cur1->next;
            highLen--;
        }
        if(ci>0){//需要创建新的结点
            struct ListNode *newNode=(struct ListNode *)malloc(sizeof(struct ListNode));
            if(newNode==NULL)
                exit(EXIT_FAILURE);
            newNode->val=ci;
            newNode->next=NULL;
            pre->next=newNode;


        }
    }
    else if(highLen==0&&ci>0){
            struct ListNode *newNode=(struct ListNode *)malloc(sizeof(struct ListNode));
            if(newNode==NULL)
                exit(EXIT_FAILURE);
            newNode->val=ci;
            newNode->next=NULL;
            pre->next=newNode;

    }
    return highNum;

}

在线编程,感觉挺奇怪的:
在平时的代码中:我们都是这样再写是OK的:

 ListNode* highNum;

但是,如果在线编译:这是不能够通过的,需要这样写才不提示编译错误。:

struct ListNode* highNum

贴上AC的结果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值