【发布时间】: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