问题描述
这是我从链表中删除节点的代码.
This is my code for deleting a node from a linked list.
vec_store
保存 seq
和 size
.变量 seq
保存向量和指针.
vec_store
holds seq
and size
. Variable seq
holds the vectors and a pointer.
出于某种原因,else if(i<s->size-1)
不起作用,这是最后一个条件.
For some reason, the else if(i<s->size-1)
doesn't work which is the last condition.
谁能解决这个问题?顺便说一下,这是C 代码.
Can anyone solve the problem? By the way this is C code.
void delete_vec(vec_store s, int i)
{
if (i<0 || s->size-1<i)
{
printf("Cannot delete vector because index %d is out of bounds
",i);
}
else if (i==0)
{
node temp;
temp = s->seq;
s->seq = s->seq->next;
s->size--;
free(temp);
}
else if(i==s->size-1)
{
node temp1, temp2;
//temp1 = malloc(sizeof (node));
temp2 = malloc(sizeof (node));
temp1=s->seq;
if(temp1->next==NULL)
{
free(temp1);
s->seq=NULL;
s->size--;
printf("s->size-1
");
}
else
{
while (temp1->next!=NULL)
{
temp2 = temp1;
temp1 = temp1->next;
}
free(temp1);
temp2->next=NULL;
s->size--;
printf("s->size-1 2
");
}
}
else if(i<s->size-1)
{
node temp1,temp2;
int j;
temp1=s->seq;
temp2 = malloc(sizeof (struct node_record));
for(j=0;j<=i-1;j++)
{
temp2=temp1;
temp1 = temp1->next;
}
free(temp1);
temp2->next=NULL;
s->size--;
}
}
推荐答案
此代码无法访问:
if(temp1->next==NULL){
free(temp1);
s->seq=NULL;
s->size--;
printf("s->size-1
");
}
...因为 temp1
是列表中的第一个元素,所以它只会在第一个元素也是最后一个元素时发生 - 这意味着 s->size
是 1,所以这会被前面的 if (i==0)
情况捕获.
...because temp1
is the first element in the list, and so it would only happen if the first element was also the last element - which implies s->size
is 1, so this would have been caught by the earlier if (i==0)
case.
这种对 temp2
的分配(出现在两个地方)是虚假的 - temp2
的值无论如何都会被覆盖,从而泄漏您分配的内存:
This allocation to temp2
(which occurs in two places) is bogus - temp2
's value gets overwritten anyway, leaking the memory you allocated:
temp2 = malloc(sizeof (node));
最后,您要问的问题可能是什么(在 if(i<s->size-1)
情况下):
Finally, what is probably the problem you're asking about lies here (in the if(i<s->size-1)
case):
free(temp1);
temp2->next=NULL;
这会将整个结尾从列表中删除.你想保留列表的尾部 - 像这样:
This chops the entire end off the list. You want to keep the tail of the list around - like this:
temp2->next = temp1->next;
free(temp1);
顺便说一下,temp2
和 temp1
是非常乏味的变量名 - previous
和 current
或某物?此外,if(i==s->size-1)
的特殊情况 完全 是不必要的 - 它应该由您为 if(isize-1)
case.
By the way, temp2
and temp1
are pretty uninspiring variable names - what about previous
and current
or something? Also, the special case for if(i==s->size-1)
is completely unnecessary - it should be handled fine by the code you have for the if(i<s->size-1)
case.
这篇关于按索引从链表中删除节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!