【问题标题】:Sum of last N nodes of a linked list链表最后 N 个节点的总和
【发布时间】:2021-05-13 09:08:35
【问题描述】:

给定的问题是我们必须找到链表的最后 n 个节点的总和。 如果列表是这样的示例:-

1->2->3->4->5->6->7

n 是3

那么答案应该是 18(从 5 + 6 + 7)。

这是我的解决方案->

Node*temp = head ; int sum = 0;int cnt = 1;
  if(n<=0){
      return 0 ;
  }
  while(cnt!=n)
  {
    temp = temp->next ;cnt+=1 ; 
  }
  temp = temp->next ;
  while(temp!=NULL)
  {
      sum+= temp->data ; temp = temp->next ;
  }

  return sum ;

编辑器正在为某些输入案例提供分段转储。我哪里错了?

【问题讨论】:

  • 嗨,如果您的问题已经解决,请考虑接受答案:) 谢谢

标签: c++ c linked-list segmentation-fault


【解决方案1】:

您的代码存在一些问题,即1)在第一个while(cnt!=n)中,您没有考虑tempnull的情况,这会导致问题:

 temp = temp->next

此外,您想对最后 'n' 个元素求和,但实际上是在尝试对前 'n' 个元素之后的元素求和。

使用递归可以更轻松地解决此问题,如 here 所示。在迭代中,一种方法是计算列表中元素的数量,然后在找到total elements - 'n'th 元素后开始对元素求和。

  if(n<=0){
      return 0;
  }
  // Let us calculate how many elements are on the list.
  Node *temp = head; 
  int total_elements = 0;
  while(temp != null)
  {
     total_elements++;
     temp = temp -> next;
  }
  int n_th = total_elements - n;
  if(n_th < 0) return 0;
  
  temp = head;
  int cnt = 0;

  // Here we do need to check temp for null 
  // because we know temp has at least n_th elements
  while(cnt != n_th)
  {
      cnt++;
      temp = temp->next;
  }
  temp = temp->next ;
  int sum = 0;
  while(temp != NULL)
  {
      sum += temp->data ; 
      temp = temp->next ;
  }

  return sum ;

另一种方法是在计算列表中元素数量的过程中,我们还将所有元素相加,然后最后我们减去不应该成为总和一部分的(初始)元素:

  if(n<=0){
      return 0;
  }
  // Let us calculate how many elements are on the list.
  Node *temp = head; 
  int total_elements = 0;
  int sum = 0;
  while(temp != null)
  {
     total_elements++;
     sum += temp->data;
     temp = temp -> next;
  }
  int n_th = total_elements - n;
  if(n_th < 0) return 0;
  
  temp = head;
  int cnt = 0;

  while(cnt != n_th)
  {
      cnt++;
      sum -= temp->data;
      temp = temp->next;
  }

  return sum ;

【讨论】:

    【解决方案2】:

    当 n 等于链表的长度时,可能会发生分段错误。

    在您的示例中,如果我们将 n 设置为 7,则 temp 指针将在 while 循环内转发 7 次。因此,它到达链表的末尾。现在,如果您在链表末尾执行temp = temp-&gt;next ;,则会出现分段错误,因为链表中没有下一个元素。

    这个问题的一个简单/天真的解决方案是:

    1. 计算列表中元素的总数。
    2. n 中减去它以获得最初必须忽略的元素数。
    3. 总结其余元素。

    当然,可能有其他/更好的方法来解决这个问题。

    【讨论】:

      【解决方案3】:

      你的问题在于这个循环

      while(cnt!=n)
        {
          temp = temp->next ;cnt+=1 ; 
        }
      

      您将temp 递增n 次。但是您甚至没有检查 temp 是否指向有效条目。是不是NULL

      其次,逻辑是错误的。您正在跳过第一个 n 数字并计算剩余数字的总和。你应该做的是得到总数,然后迭代上面提到的while循环直到total_num - n次。之后做剩余数字的总和。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-04-08
        • 1970-01-01
        • 2021-10-20
        • 2021-12-20
        • 2016-06-11
        • 2013-03-25
        • 1970-01-01
        相关资源
        最近更新 更多