这是我的代码,它删除了last的列表项。我试图实现链表概念。
void del(list** head,int da,int n) { //da-for no of elements to be
list *l1; //deleted from end.
int n1 = n-da; //n-for total no of elements in list
if (n1 == 0)
*head = NULL;
else {
l1 = *head;
n1 = n1-1;
while(n1) {
l1 = l1->next;
n1--;
}
l1->next=NULL;
}
}
包含此代码后,我收到SIGSEGV错误。这是什么意思?请帮我这个代码。我最近开始学习数据结构。我没有那么多的编程经验,但我知道C中的一些基础知识。
答案 0 :(得分:1)
如果你问的是"什么是SIGSEGV?"它是Segmentation Fault的错误信号。现在,如果您想知道导致它的原因,那么void del(list** head,int da,int n)
da < n
函数会在int n1 = n - da; // Assume n < da
...
while(n1) { // n would be 0< therefor: n1 will never equal 0 causing infinite loop
l1 = l1->next;
n1--;
}
时导致undefined behavior,因为它会导致逻辑错误,从而导致无限循环:
list->next == null
如果您尝试从链接列表背面删除n个元素,可以使用以下几种解决方案:
迭代到链表的尾部或linked link
,然后向后迭代每次迭代删除正在传递的节点,直到 n 节点被删除
另一种方法是使用一个类[22:57:51]
[22:57:51]Errors in C:\path\to\project\Server\Server.csproj
[22:57:51] Package Microsoft.AspNetCore 2.0.0 is not compatible with net462 (.NETFramework,Version=v4.6.2). Package Microsoft.AspNetCore 2.0.0 supports: netstandard2.0 (.NETStandard,Version=v2.0)
[22:57:51] Package Microsoft.AspNetCore.Mvc 2.0.0 is not compatible with net462 (.NETFramework,Version=v4.6.2). Package Microsoft.AspNetCore.Mvc 2.0.0 supports: netstandard2.0 (.NETStandard,Version=v2.0)
[22:57:51] One or more packages are incompatible with .NETFramework,Version=v4.6.2.
[22:57:51] Package Microsoft.AspNetCore 2.0.0 is not compatible with net462 (.NETFramework,Version=v4.6.2) / win7-x86. Package Microsoft.AspNetCore 2.0.0 supports: netstandard2.0 (.NETStandard,Version=v2.0)
[22:57:51] Package Microsoft.AspNetCore.Mvc 2.0.0 is not compatible with net462 (.NETFramework,Version=v4.6.2) / win7-x86. Package Microsoft.AspNetCore.Mvc 2.0.0 supports: netstandard2.0 (.NETStandard,Version=v2.0)
[22:57:51] One or more packages are incompatible with .NETFramework,Version=v4.6.2 (win7-x86).
[22:57:51]
[22:57:51]Errors in C:\path\to\project\Server\Server.csproj
[22:57:51] Package Microsoft.Extensions.FileProviders.Physical 2.0.0 is not compatible with netcoreapp2.0 (.NETCoreApp,Version=v2.0). Package Microsoft.Extensions.FileProviders.Physical 2.0.0 supports: netstandard2.0 (.NETStandard,Version=v2.0)
[22:57:51] Package Microsoft.VisualStudio.Web.CodeGeneration.Contracts 2.0.0 is not compatible with netcoreapp2.0 (.NETCoreApp,Version=v2.0). Package Microsoft.VisualStudio.Web.CodeGeneration.Contracts 2.0.0 supports: netstandard2.0 (.NETStandard,Version=v2.0)
[22:57:51] One or more packages are incompatible with .NETCoreApp,Version=v2.0.
[22:57:51]Process exited with code 1
来存储头节点,尾节点和链表的大小。然后从列表的尾部迭代,删除 n O(N)节点或迭代到 length - n ,然后开始删除,直到你到达尾部
答案 1 :(得分:0)
我认为当您使用n1
的值太大而调用delete时,您可能会遇到段错误。在这种情况下你的循环:
while(n1) {
l1 = l1->next;
n1--;
}
将走得太远并访问*l1
l1 == NULL
。我没有按照您的del
函数应该完全执行的操作,但这是您的segfault的来源。如果您从main移除对del
的呼叫,则不会出现此类问题。