LeetCode:两数之和(C语言版)

Posted 想考北航的小刺猬

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode:两数之和(C语言版)相关的知识,希望对你有一定的参考价值。

两数相加

在这里插入图片描述

这里先不多说,直接上代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
    struct ListNode* p = l1 ,* q = l2 ,* r = NULL ,* re = NULL ,* cur = NULL;
    int num = 0;

    // 处理第一个结点
    r = (struct ListNode*)malloc(sizeof(struct ListNode)) ;
    re = r;
    cur = r ;
    if(p -> val + q -> val >= 10){
        num = 1;
        r -> val = p -> val + q -> val - 10;
        r -> next = NULL ; 
    }
    else{
        r -> val = p -> val + q -> val;
        r -> next = NULL ;
    }
    p = p -> next;
    q = q -> next;

    //处理中间部位等长结点
    while(p != NULL && q != NULL){
        r = (struct ListNode*)malloc(sizeof(struct ListNode)) ;
        r -> val = p -> val + q -> val + num; 
        if(r -> val < 10){
            num = 0;
            cur -> next = r ; 
            cur = r ;
            r -> next = NULL ;
        }
        else{
            r -> val = r -> val - 10 ;
            num = 1;
            cur -> next = r ; 
            cur = r ;
            r -> next = NULL ;
        }
        p = p -> next;
        q = q -> next; 
    }

    //p的长度小于q时,处理q后部剩余结点
    if (p == NULL && q != NULL){
        cur -> next = q;
        while(q != NULL)
            if(q -> val + num < 10){
                q -> val = q -> val + num;
                num = 0 ;
                return re;
            }
            else{
                q -> val = 0 ;
                num = 1;
                cur = q;
                q = q -> next ;
            }
        r = (struct ListNode*)malloc(sizeof(struct ListNode));
        cur -> next = r;
        r -> val = 1;
        r -> next = NULL;
        return re;
    }

    //q长度小于p时,处理p后部剩余结点
    else if(q == NULL && p != NULL){
        cur -> next = p;
        while(p != NULL)
            if(p -> val + num < 10){
                p -> val = p -> val + num;
                num = 0;
                return re;
            }
            else{
                p -> val = 0 ;
                num = 1;
                cur = p;
                p = p -> next ;
            }
        r = (struct ListNode*)malloc(sizeof(struct ListNode));
        cur -> next = r;
        r -> val = 1;
        r -> next = NULL;
        return re;
    }

    //如果处理完最大长度的结点后仍有进位,最后建立一个结点
    if(num == 1){
        r = (struct ListNode*)malloc(sizeof(struct ListNode));
        cur -> next = r;
        r -> val = 1;
        r -> next = NULL;
    }
    return re;
}

希望对大家有所帮助!

以上是关于LeetCode:两数之和(C语言版)的主要内容,如果未能解决你的问题,请参考以下文章

p5 不用+-求两数之和 (leetcode371)

Python版[leetcode]1. 两数之和(难度简单)

LeetCode001-简单- 两数之和

Leetcode 1. 两数之和(带图)

LeetCode刷题 1. Two Sum 两数之和 详解 C++语言实现 java语言实现

C++&Python 描述 LeetCode 1.两数之和