c - 从链表中删除节点的功能无法正常工作
问题描述
void del(struct node *l,int n) {
struct node *temp1=(struct node*)malloc(sizeof(struct node));
temp1=l;
if (l==NULL) {
printf("list already empty");
}
else if (n==1) {
l=l->next;
free(temp1);
}
else {
struct node *temp2=(struct node*)malloc(sizeof(struct node));
temp2=l;
int i,j=1;
while (i<(n-1)) {
temp1=temp1->next;
i++;
}
while (j<n) {
temp2=temp2->next;
j++;
}
temp1->next=temp2->next;
free(temp2);
}
}
所以这是我为从单链表中删除元素而编写的函数,但它没有提供所需的输出。有人可以帮帮我吗?
解决方案
你的函数不正确。至少由于这些没有意义的内存分配,它会产生内存泄漏
struct node *temp1=(struct node*)malloc(sizeof(struct node));
struct node *temp2=(struct node*)malloc(sizeof(struct node));
第二个参数应该是无符号整数类型,并且列表中的位置应该从 0 开始。
该函数不应发出任何消息。由函数的调用者决定是否在调用函数后发出消息。
该函数可以通过以下方式定义
int del( struct node **head, size_t n )
{
while ( *head != NULL && n-- )
{
head = &( *head )->next;
}
int success = *head != NULL;
if ( success )
{
struct node *tmp = *head;
*head = ( *head )->next;
free( tmp );
}
return success;
}
如果在 main 中声明了一个指向头节点的指针,例如
struct node *head = NULL;
// filling the list
然后可以调用该函数,例如
size_t n = some_position;
del( &head, n );
或者
if ( del( &head, n ) )
{
printf( "The node at position &zu is successfully deleted.\n", n );
}
其中 n 是列表中的某个位置。
推荐阅读
- mathjax - 如何使用mathjax在网页中添加表格
- javascript - 如何设置transform translate3d的持续时间或延迟我正在尝试垂直旋转木马
- php - 如何在mysql数据库中存储注销时间?
- javascript - Angular 6:如何防止一个 Observable 中的 2 个订阅变量相互级联
- java - 在 RPG 中创建选项的最佳方式
- javascript - React App CSS 过渡非常慢
- html - 如何确定图像中某个区域的颜色 html 代码
- c# - Unity Object Pooling with Scroll Rect 实现无尽地图
- plpgsql - 在 PLPGSQL 中遇到 RETURN 问题
- python - 在pygame中单击按钮