c - 如何反转链表
问题描述
我正在尝试反转返回反转列表的链接列表。
typedef struct lligada
{
int valor;
struct lligada *prox;
} *LInt;
这是我的功能:
LInt reverseL (LInt l){
LInt aux = malloc (sizeof(struct lligada));
if(l != NULL){
while( l -> prox != NULL){
aux = l-> prox;
aux -> prox = l;
l = l-> prox;
}
}
else return NULL;
return aux;
}
你能帮我吗 ?
我试过这样做:
if(l != NULL){
if(l -> prox == NULL) {
aux = l;
}
else{
while( l -> prox != NULL){
aux = l-> prox;
aux -> prox = l;
l = l-> prox;
}
aux -> prox = l;
}
}
这是一个好主意吗 ?
解决方案
首先,在这种情况下,对 malloc 的调用是无用的,它是内存泄漏。
此代码段不起作用,因为您在前两个元素之间创建了无限循环
if (l != NULL)
{
if (l->prox == NULL)
{
aux = l;
}
else
{
while (l->prox != NULL)
{
aux = l->prox;
aux->prox = l;
l = l->prox;
}
aux->prox = l;
}
}
你可以这样改变
LInt new_head, aux;
new_head = NULL;
while (l != NULL)
{
aux = l->prox;
l->prox = new_head;
new_head = l;
l = aux;
}
return new_head;
推荐阅读
- sql - 聚合重叠段以测量有效长度
- vba - Rubberduck VBA:什么会导致解析器错误?
- javascript - 比较 3 个数组以创建一个新字符串
- python - postgres 从 jsoncolumn 中删除 json
- azure - 使用 .pfx 证书从头开始实现 HDInsight 部署自动化
- javascript - 在 JS/React 中,如何将数组属性存储到新数组中以显示新数组值?
- java - Java 计划任务是否在 AWS Auto Scaling 组的所有 EC2 实例上运行?
- vb.net - Oracle 查询中的数字字段在零时返回变量结果
- javascript - 引导导航栏:让搜索按钮工作
- apache-spark - Kubernestes 独立火花:spark-shell 在从属设备上工作,而不是在主设备上工作:初始作业没有接受任何资源;