到目前为止,我已经成功地从第I个索引中删除了所有内容,但我需要能够将第I个之前的节点连接到第I个之后的节点,这就是我目前所拥有的。
LinklistNode* remove_node(LinklistNode* list_head, int index){
if(list_head != NULL){
LinklistNode* temp;
if(list_head-> next ==NULL){
temp = list_head;
list_head = NULL;
}
else{
LinklistNode* list_pointer = list_head;
LinklistNode* next_list_pointer = list_pointer->next;
while(next_list_pointer->next != NULL && index > 0){
index--;
list_pointer = next_list_pointer;
next_list_pointer = next_list_pointer->next;
}
temp = next_list_pointer;
list_pointer->next = NULL;
}
free(temp);
}
return list_head;
}
要链接索引前后的节点,请将list_pointer->next
指向next_list_pointer->next
while(next_list_pointer->next != NULL){
index--;
if (index == 0) break;
list_pointer = next_list_pointer;
next_list_pointer = next_list_pointer->next;
}
temp = next_list_pointer;
list_pointer->next = temp->next;
为了在第i个元素之前连接节点,请使用list_pointer。有类似的东西…
while(next_list_pointer != NULL || index != 0){
list_pointer = list_pointer->next;
next_list_pointer = list_pointer->next;
}
if(next_list_pointer == NULL){
printf("Invalid index given. Nothing deleted.n");
//Do not delete otherwise an error will be given
return list_head;
} else {
//Valid index was given
list_pointer->next = next_list_pointer->next;
free(next_list_pointer);
return list_head;
}
这应该几乎涵盖了删除部分,只是一定要包括你的基本情况。
使用指向节点的指针对指针的替代方法:
LinklistNode* remove_node(LinklistNode* list_head, int index)
{
LinklistNode **ppNode = &list_head;
if(list_head == NULL)
return NULL;
while(index--){
ppNode = &((*ppNode)->next);
if(*ppNode == NULL) /* if index not in list */
return list_head; /* just return */
}
*ppNode = (*ppNode)->next; /* delete node */
return list_head;
}