《leetCode》:add two num

来源:互联网 发布:如何投诉网络运营商 编辑:程序博客网 时间:2024/06/05 04:09

《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
原创粉丝点击