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

链表相加(二)

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

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

/**
 * 
 * @param head1 ListNode类 
 * @param head2 ListNode类 
 * @return ListNode类
 */
struct ListNode* ReverseList(struct ListNode* pHead){
    struct ListNode* res = NULL;
    struct ListNode* cur = pHead;
    while(cur){
        struct ListNode* temp = cur->next;
        cur->next = res;
        res = cur;
        cur = temp;
    }
    
    return res;
}

struct ListNode* addInList(struct ListNode* head1, struct ListNode* head2 ) {
    // write code here
    struct ListNode* l1 = ReverseList(head1);
    struct ListNode* l2 = ReverseList(head2);
    struct ListNode* res = NULL;
    int cnt = 0;
    
    while(l1 || l2){
        int x1 = l1 == NULL ? 0 : l1->val;
        int x2 = l2 == NULL ? 0 : l2->val;
        
        l1 = l1 == NULL ? NULL : l1->next;
        l2 = l2 == NULL ? NULL : l2->next;
      
        int sum = x1 + x2 + cnt;
        cnt = sum/10;
        
        struct ListNode* temp = (struct ListNode*)malloc(sizeof(struct ListNode));
        temp->val = sum%10;
        
        temp->next = res;
        res = temp;
        
    }
    
    if(cnt > 0){
        struct ListNode* temp = (struct ListNode*)malloc(sizeof(struct ListNode));
        temp->val = cnt;
        temp->next = res;
        res = temp;
    }
    
    return res;
}

全部评论

相关推荐

努力的小明a:项目看着很眼熟,施磊老师吧,我也学的这个😋我当时是把rpc框架做成了一个分布式网盘,这是一个项目,然后muduo库做成集群即时通讯,又用QT做了个交互的客户端,这样又一个项目,然后一个轻量redis,一个CAD,总共四个项目,投了三个月就今天2月份一个小厂Qt offer,然后后面想开了,Qt啥的都能干,这个月get了个北京大厂的offer,做java后端,人生就是这么魔幻,现在就在去北京入职的路上
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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