建议的解决方案
hol
是一个指针,所以hol[n-1]
等可能不会引用entry
内存中的结构,请考虑何时n = 0
. 无论哪种方式,这都不是您应该访问列表结构中不同条目的方式。
对于单链表,您必须考虑 3 种情况,
- 如果
n = 0
(即第一个条目)正在被删除
- 如果要删除的条目在列表中的某处
- 如果条目是列表中的最后一个条目。
我的理解number
是列表条目的索引,并且您已经为列表条目使用了动态内存分配。此外,由于您似乎使用的是 C89 标准(它不允许循环变量初始化),我已尽我所能将下面的代码改编为 C89,但我自己不使用该标准:
int delete_contact(unsigned int n) {
int i = 0;
int k = 0;
// Check if the index refers to an element not included in the list
if (n > count) { return -1; }
entry* tmp = hol;
if (n == count - 1) {
// Iterate to the last entry
while (tmp->next) {
tmp = tmp->next;
}
free(tmp); // Free the list entry
// Decrement the global counter keeping track of the
// amount of list elements
count--;
// No need to edit the contact indexes
return;
}
entry* remaining_list = hol;
if (n == 0) {
// Free the head of the list
hol = hol->next;
remaining_list = hol;
free(tmp); // tmp points to the head of the list already
} else {
// The list entry is somewhere inside the list
int idx = 0;
// Iterate until tmp points to the n-1:th entry
while (idx < n - 1) {
tmp = tmp->next;
idx++;
}
entry *to_be_freed = tmp->next; // n:th entry
tmp->next = tmp->next->next;
remaining_list = tmp->next;
free(to_be_freed);
}
// Decrement the contact index on all the remaining entries
while (remaining_list) {
remaining_list->number--;
remaining_list = remaining_list->next;
}
// Decrement the global counter keeping track of the
// amount of list elements
count--;
return 0;
}
提示
通过创建一个更具表现力的列表接口可能会更好地为您服务,可能是一个不绑定到存储在其中的值的接口。这样你就可以创建一个
list_size()
函数并删除全局计数器。
这里有一些东西可以帮助您入门:
typedef struct node {
void* value;
struct node* next;
} node;
typedef struct list {
node* head;
node* tail;
size_t len;
} list;
参考资料