gpt4 book ai didi

c - 使用链表添加两个数字

转载 作者:行者123 更新时间:2023-11-30 19:36:20 26 4
gpt4 key购买 nike

2. Add Two Numbers

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

我已经完成了 Leetcode 中第二题的代码。当我提交答案时,当输入是两个零时,我遇到了运行时错误。但是当我使用自己的自定义测试用例时,它看起来工作得很好。

我仔细检查了我的代码,仍然找不到错误所在。你能帮我吗?

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode* p1;
struct ListNode* p2;
struct ListNode* head;
head = (struct ListNode*)malloc(sizeof(struct ListNode*));
struct ListNode* cur = head;

p1 = l1; p2 = l2;

int sum, carry = 0, x, y;

while(p1 || p2)
{
//Assign the values of the listnode to x and y.
if(p1 != NULL) x = p1 -> val; else x = 0;
if(p2 != NULL) y = p2 -> val; else y = 0;
sum = x + y + carry;

//Declare a new node nxt(next) and insert it after the current node
struct ListNode* nxt;
nxt = (struct ListNode*)malloc(sizeof(struct ListNode*));
nxt -> val = sum % 10;
carry = sum / 10;

cur -> next = nxt;
cur = cur -> next;

if(p1 != NULL) p1 = p1 -> next;
if(p2 != NULL) p2 = p2 -> next;
}

if(carry > 0)
{
struct ListNode* nxt;
nxt = (struct ListNode*)malloc(sizeof(struct ListNode*));
nxt -> val = carry;
cur -> next = nxt;
}

head = head -> next;

return head;
}

错误:

The error

自定义测试用例:

custom testcase

最佳答案

So how to edit the code then?

正如约翰·库格曼上面所写:

    head = malloc(sizeof(struct ListNode));

nxt = malloc(sizeof(struct ListNode));

关于c - 使用链表添加两个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41020720/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com