【问题标题】:What's wrong in my link-list code for C? `Add Two Numbers` [closed]我的 C 链接列表代码有什么问题? `添加两个数字` [关闭]
【发布时间】:2021-04-01 03:53:17
【问题描述】:

关于 Leetcode 的问题 2:

添加两个数字。

我的代码在这里:

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
  struct ListNode* result;  
  volatile bool carry = false;
  while ((l1 != NULL) || (l2 != NULL) ) {
    result = (struct ListNode*)malloc(sizeof(struct ListNode) );
    result->next = NULL;
    int v1 = 0;     
    if (l1 != NULL) {
      v1 = l1->val;
      l1 = l1->next;
    }
    
    int v2 = 0;     
    if (l2 != NULL) {
      v2 = l2->val;
      l2 = l2->next;
    }
        
    int sum = v1 + v2;
    if (carry == true)
      sum += 1;
    carry = (sum > 9);
        
    result->val = sum%10;
    printf("result->val: %d, sum: %d, carry: %d\n",result->val,sum,carry); 
    //result = result->next;

  }
  
  return result;
}

输入

[2,4,3]
[5,6,4]

期待

[7,0,8]

标准输出

result->val: 7, sum: 7, carry: 0
result->val: 0, sum: 10, carry: 1
result->val: 8, sum: 8, carry: 0

真的出来了:

[8]

我觉得可能是损失

result = result->next;

在while循环中,

所以我在printf()之后添加它。

但输出似乎为空

[]

我的代码有什么问题?

【问题讨论】:

  • 进行基本调试。使用调试器单步执行代码并在运行时对其进行检查。如果您在这里仍然需要帮助,请提供可以重现问题的最少完整代码。见:How to create a Minimal, Reproducible Example
  • 我们无权访问 leetcode 测试。您需要显示构造传递给函数的链表的代码。
  • result = (struct ListNode*)malloc(sizeof(struct ListNode) ); 你每次都在覆盖头节点。使用两个变量 - 一个用于头节点(要返回),一个用于最后一个节点(用于添加下一个节点)。
  • 因为result-&gt;next在每次迭代中都变成NULL,运行result = result-&gt;next;只会使result等于NULL
  • 基本上你失去了链表的头部:(

标签: c linked-list


【解决方案1】:

您的问题是您在每次迭代期间都重新分配了 result 的值。因此,无论有多少次迭代,您都只会有一个长度为一的链表。此外,您还会泄漏大量内存。

相反,您应该这样做

struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
  struct ListNode *result = NULL; // Initialize the variable.
  struct ListNode *last = NULL;
  bool carry = false; // There is no need for this to be volatile.
  while ((l1 != NULL) || (l2 != NULL) ) {
    struct ListNode *temp = malloc(sizeof(struct ListNode)); // You shouldn't cast the result of malloc.
    if ( !temp ) {
        // handle the error somehow
    }
    temp->next = NULL;
    int v1 = 0;     
    if (l1 != NULL) {
      v1 = l1->val;
      l1 = l1->next;
    }
    
    int v2 = 0;     
    if (l2 != NULL) {
      v2 = l2->val;
      l2 = l2->next;
    }
        
    int sum = v1 + v2;
    if (carry)
      sum++;
    carry = (sum > 9);
        
    temp->val = sum%10;
    printf("result->val: %d, sum: %d, carry: %d\n",temp->val,sum,carry); 

    if ( last ) {
      last->next = temp;
    }
    else {
      result = temp;
    }
    last = temp;
  }
  
  return result;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-23
    • 1970-01-01
    • 2015-02-16
    • 1970-01-01
    • 1970-01-01
    • 2014-07-17
    • 2013-02-11
    相关资源
    最近更新 更多