c - 使用递归删除链表中所有出现的数字
问题描述
我想编写一个程序,使用递归从一个简单的链表中删除所有出现的数字,所以我尝试了但我遇到了问题:我编写的程序会擦除列表中的所有出现但它不会删除那个存在于开头(出现在第一个节点处),这是C中的代码:
typedef struct list {
int data;
struct list *next;
} list;
list *delete(int x, list *head) {
if (head->next == NULL)
return head;
list *newnode = delete(x, head->next);
if (newnode->data == x) {
head->next = head->next->next;
free(newnode);
}
return head;
}
我希望有人可以帮助我改进我的算法,在此先感谢。
解决方案
这段代码:
if(head->next == NULL)
return head;
显式地使函数返回任何 1 元素列表不变。这会产生您描述的问题,因此在那里没有任何意义。
我想应该可以递归地制定列表元素的删除,尽管它肯定不是一种常见/典型/好方法。
这可能有效,未经测试:
list * delete(list *head, int value)
{
if (head == NULL)
return NULL;
if (head->data == value)
{
list * tail = head->next;
free(head);
return delete(tail, value);
}
// List was not empty and did not start with the value,
// so set the tail of the list to the tail without the value.
head->next = delete(head->next, value);
return head;
}
推荐阅读
- jwt - 如何在前端安全地存储 JWT
- c - 获取正确的 sscanf 格式以打印字符串和整数
- amazon-web-services - 我创建了一个 ECS 容器,如何将域绑定到它?
- javascript - AJAX查询成功时如何调用PHP函数
- ios - 在 UIScrollView 内旋转 UIImageView 使 X 和 Y 倒置。为什么?
- javascript - 如何在 android javascript 中设置修复 url?
- javascript - enctype="multipart/form-data" 总是返回空输入,但 multer 必须工作我们如何解决这个问题?
- android - 如何使用 LiveData 在 ViewModel 中启动 Kotlin 协程
- security - 如何将扫描的 IP 地址转移到蜜罐?
- javascript - 以 PDF 格式从数据库加载缓冲区数据