我想通过节点的索引号(序列号)从链表中删除给定的节点。所以我试图在我的函数中做的是,首先我接受了用户输入的索引号。然后我使用了两个节点类型指针temp
和current
. 我开始遍历列表,current
当节点的索引号与用户输入匹配时,我尝试删除该节点。到目前为止它是正确的。我面临删除逻辑的问题。这是我尝试过的代码:
void delete_node(struct node **start,int index_no)
{
int counter=0;
struct node *temp, *current;
temp=(struct node *)malloc(sizeof(struct node));
current=(struct node *)malloc(sizeof(struct node));
current=*start;
while(current->next!=NULL)
{
counter++;
if(counter==index_no)
{
temp= current->next;
free(current);
/*I guess some code is missing here. Help me finding the logic.*/
}
else
{
printf("\n The index number is invalid!!");
}
}
}
注释部分缺少删除逻辑。另外,我有一种感觉,这段代码不节省空间和时间。如果是这样,请建议一种使其更紧凑的方法。