力扣崩溃题:链表相加

复制代码
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){

    int sum=0, carry = 0;
    struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* p = head;

    while(l1 || l2 || carry) {
        sum = 0;
        if(l1) {
            sum += l1->val;
            l1 = l1->next;
        }

        if(l2) {
            sum += l2->val;
            l2 = l2->next;
        }
        sum += carry;

        struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
        newNode->val = sum >=10 ? sum%10 : sum;
        newNode->next = NULL;            
        carry = sum >=10 ? 1 : 0;
        
        p->next = newNode;
        p = p->next;
    }
    return head->next;

}

由于力扣的用例太大了,导致笔者的方法用不了,就是下面的,力扣你无敌了

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


struct ListNode* addTwoNumbers(struct ListNode* head1, struct ListNode* head2){
    if(head1->val+head2->val<10&&head1->next==NULL&&head2->next==NULL)
    {
        head1->val=head1->val+head2->val;
        return head1;
    }
     if(head1->val+head2->val==10&&head1->next==NULL&&head2->next==NULL)
    {
        head1->val=0;
        struct ListNode*point3=(struct ListNode*)malloc(sizeof(struct ListNode));
    point3->next=NULL;
    point3->val=1;
    head1->next=point3;
        return head1;
    }
long long count1=0;
long long count2=0;
long long arr1[1000];
long long arr2[1000];
int i=0;
int j=0;
struct ListNode*point1=head1;
struct ListNode*point2=head2;
while(point1)
{
    arr1[i]=point1->val;
    i++;
    point1=point1->next;
}
while(point2)
{
    arr2[j]=point2->val;
    j++;
    point2=point2->next;
}
long good=1;
long bad=1;
for(int x=0;x<i;x++)
{
    count1=count1+good*arr1[x];
    good=good*10;
}
for(int x=0;x<j;x++)
{
    count2=count2+bad*arr2[x];
    bad=bad*10;
}
long long total=count1+count2;
int t=10;
int a=1;
int z=0;
long arr5[1000];
long count3=total;
while(count3!=0)
{
  arr5[z]=count3%10;
  z++;
  count3=count3/10;
}
free(head1);
head1=(struct ListNode*)malloc(sizeof(struct ListNode)*z);
head1->val=arr5[0];
head1->next=NULL;
struct ListNode*point4=head1;
for(int x=1;x<z;x++)
{
    struct ListNode*point3=(struct ListNode*)malloc(sizeof(struct ListNode));
    point3->next=NULL;
    point3->val=arr5[x];
    point4->next=point3;
    point4=point4->next;
}
return head1;
}
相关推荐
_殊途1 小时前
《Java HashMap底层原理全解析(源码+性能+面试)》
java·数据结构·算法
珊瑚里的鱼4 小时前
LeetCode 692题解 | 前K个高频单词
开发语言·c++·算法·leetcode·职场和发展·学习方法
秋说5 小时前
【PTA数据结构 | C语言版】顺序队列的3个操作
c语言·数据结构·算法
lifallen6 小时前
Kafka 时间轮深度解析:如何O(1)处理定时任务
java·数据结构·分布式·后端·算法·kafka
liupenglove6 小时前
自动驾驶数据仓库:时间片合并算法。
大数据·数据仓库·算法·elasticsearch·自动驾驶
python_tty7 小时前
排序算法(二):插入排序
算法·排序算法
然我7 小时前
面试官:如何判断元素是否出现过?我:三种哈希方法任你选
前端·javascript·算法
F_D_Z8 小时前
【EM算法】三硬币模型
算法·机器学习·概率论·em算法·极大似然估计
秋说8 小时前
【PTA数据结构 | C语言版】字符串插入操作(不限长)
c语言·数据结构·算法
凌肖战9 小时前
力扣网编程135题:分发糖果(贪心算法)
算法·leetcode