c - 链表中的排序插入程序
问题描述
我是数据结构的初学者,现在正在学习链表。我遇到了一个关于排序插入的程序,其中我有一个 add() 函数来按排序顺序添加节点
/*Linked List program to add ascending order sorted nodes in
the list */
#include <stdio.h>
#include <stdlib.h>
enter code here
struct node {
int data ;
struct node link;
};
void add(struct node **q,int num){
struct node *r,*temp = *q;
r = malloc(sizeof(struct node )); //Data Allocated
r->data = num;
if(*q==NULL ||(*q)->data >num){
*q = r;
(*q)->link = temp;
}else{
while(temp !=NULL){
if(temp->data <=num &&(temp->link->data >num
||temp->link==NULL)){
r->link = temp->link;
temp->link=r;
return;
}
temp = temp->link;
}
}
}
void main(){
struct node *p;
p = NULL;
}
我希望按升序添加节点,但是当我输入数据时会显示错误。我正在使用代码块在 C 中运行程序
我认为它必须与结束条件 temp->link == null 相关,但我无法确定该部分代码的确切条件。请帮助!
解决方案
结构的定义
struct node
不正确。我认为这是一个错字。它应该是struct node *link;
您遍历循环的条件不正确。如评论中所述,您正在访问
temp->link
以防万一NULL
。您没有检查要添加的数字大于所有数字并且要添加到列表末尾的条件。
修改后的功能如下。
void add(struct node **q,int num){
struct node *r,*temp = *q;
r = malloc(sizeof(struct node )); //Data Allocated
r->data = num;
r->link = NULL;
if(*q==NULL ||(*q)->data >num){
*q = r;
(*q)->link = temp;
}else{
while(temp->link !=NULL){
if(temp->data <=num &&(temp->link->data >num)){
r->link = temp->link;
temp->link=r;
return;
}
temp = temp->link;
}
temp ->link = r; // add at the end as not added at any other location.
}
}
推荐阅读
- reactjs - 将按钮 ID 设置为单击时的状态
- swift - 简单的编辑画面
- jenkins-pipeline - 无法将 X 射线报告导入 Jira
- wordpress - IBM Watson Assistant:使用新生成的 API 详细信息仍会在我的 Wordpress 站点上部署旧助手
- javascript - React - 使用 usestate 钩子推送数组
- python - 获取将值添加到列表中的所有可能结果
- mysql - 更新到 8.0.22 后 MySQL 服务器 InnoDB posix_fallocate() 错误
- c# - 从 SAP 将字符串转换为图像
- python - Powershell 显示“ObjectNotFound”
- typescript - 为什么服务构造函数在 Nest.js 控制器中没有 new 的情况下工作