一个特殊的链表C函数
我需要写一个C函数,它在链表上工作,如下所示:一个特殊的链表C函数,c,list,C,List,我需要写一个C函数,它在链表上工作,如下所示: struct list { int value; struct list * next_ptr; } 此函数将阈值和列表本身作为输入,然后必须: 1) 将+1添加到列表中的每个整数中 2) 然后检查哪个已超过阈值并将其移除 3) 将已删除元素的数量作为输出 列表必须从最小到最大排序(例如:1234是,432 1或1234否…) 它应该如何工作的示例: 列表中的值:2 4 6 8 阈值:6 列表变为3 5 7 9 函数删除7和9-
struct list {
int value;
struct list * next_ptr;
}
此函数将阈值和列表本身作为输入,然后必须:
1) 将+1添加到列表中的每个整数中2) 然后检查哪个已超过阈值并将其移除
3) 将已删除元素的数量作为输出 列表必须从最小到最大排序(例如:1234是,432 1或1234否…) 它应该如何工作的示例:
- 列表中的值:2 4 6 8
- 阈值:6
- 列表变为3 5 7 9
- 函数删除7和9->3 5未删除
- 输出为2,因为已删除2个值
int thres_erase(struct list ** ptrptr, int thres){
int count;
visit_incr(ptrptr);
while (*ptrptr != NULL){
if ((*ptrptr)->value > thres){
consume(ptrptr);
count ++;
ptrptr= &((*ptrptr)->next_ptr);
}
else
ptrptr= &((*ptrptr)->next_ptr);
}
return count;
}
(Count是已删除元素的数量)
使用的其他2个函数(它们实际上工作正常):
我正在寻找一种不会彻底改变函数的解决方案,只要让它工作就行了…我看到的第一个问题是,当您调用“访问增量”时,它会将ptrpr更新到列表的末尾,因此您的while循环永远不会运行
visit_incr(ptrptr);
while (*ptrptr != NULL){
通常,您应该学习附加调试器并逐步完成代码,或者至少使用printfs,这样您就可以真正看到代码在做什么。否则编码将非常痛苦。您的ptrptr将增加两次!先进的
consume(), *ptrptr = (*ptrptr)->next_ptr;
又在
thres_erase(), ptrptr= &((*ptrptr)->next_ptr);
选择一个
编辑
在consume()函数中,您不必检查
if (*ptrptr != NULL){...}
因为ptrptr已经是了!=NULL,在thres_erase()中
编辑:代码
在你的主要
更改thres_erase()、consume()
valter您能描述一下当前代码的工作方式吗?调试器在您提到的同一行(带循环的那一行)上说“SIGSEGV”太棒了。这意味着调用它时ptrptr==NULL,并且正在取消引用它。不足为奇,因为正如我在回答中所说,visit_incr已将其递增为NULL。那么我应该如何修复此问题?
if (*ptrptr != NULL){...}
while (*ptrptr != NULL){...}
//Your code...
struct list *temp_ptr = NULL;
temp_ptr = head_ptr; //head_ptr points to the first node
visit_incr(&temp_ptr);
if(head_ptr != NULL){
temp_ptr = head_ptr;
count = thres_erase(&temp_ptr, thres); //For all nodes except the first one
temp_ptr = head_ptr;
if(temp_ptr->value > thres){temp_ptr = temp_ptr->next_ptr; free(head_ptr); count++;}
head_ptr = temp_ptr;
}
else{printf("No nodes in the list \n");}
//print your list
temp_ptr = head_ptr;
while(temp_ptr != NULL){
printf("%d ", temp_ptr->value);
temp_ptr = temp_ptr->next_ptr;
}
//Your code...
int thres_erase(struct list **ptrptr, int thres){
int count;
struct list *temp;
temp = *ptrptr;
while(temp->next_ptr != NULL){
if( (temp->next_ptr)->value > thres){
count++;
consume( &temp );
}
else{
temp = temp->next_ptr;
}
}
return count;
}
void consume (struct list ** ptrptr){
struct list *tmp_ptr;
tmp_ptr = (*ptrptr)->next_ptr;
(*ptrptr)->next_ptr = ((*ptrptr)->next_ptr)->next_ptr;
free(tmp_ptr);
return;
}