51,411
社区成员
发帖
与我相关
我的任务
分享代码如下
#include<stdio.h>
#include<malloc.h>
typedef struct N{
int data;
struct N *next;
}*node,len;
typedef int (*fun_t)(int,int);
//函数声明:
int com_up(int a,int b);
int com_down(int a,int b);
void OrderInsert(node &L,int e,fun_t compare);
void OrderInput(node &L,fun_t compare);
void list_shower(node L);
int main(){
//创建链表头节点并初始化:
node La,Lb;
La->data=0;
La->next=NULL;
Lb->data=0;
Lb->next=NULL;
//生成有序链表
OrderInput(La,com_up);
//OrderInput(Lb,com_up);
list_shower(La);
//list_shower(Lb);
return 0;
}
//compare函数:
int com_up(int a,int b){
if(a<b) return 1;
else return 0;
}
int com_down(int a,int b){
if(a>b) return 1;
else return 0;
}
//OrderInsert函数:
void OrderInsert(node &L,int e,fun_t compare){
if(L->next==NULL){
node n= (node)malloc(sizeof(len));
n->data=e;
n->next=NULL;
L->next=n;
}else{
node n=(node)malloc(sizeof(len));
node m=L->next;
while(compare(m->data,e)==0)
m=m->next;
n->data=e;
n->next=m->next;
m->next=n;
}
}
//OrderInput函数:
void OrderInput(node &L,fun_t compare){
printf("请输入逐次输入数据(输入-1停止):\n");
int e;
scanf("%d",&e);
while(e!=-1){
OrderInsert(L,e,compare);
scanf("%d",&e);
}
}
//链表输出函数list shower:
void list_shower(node L){
node n=L->next;
while(n!=NULL){
printf("%d ",n->data);
n=n->next;
}
printf("\n");
}
运行结果如下:

你的程序存在一些问题导致直接结束。在 main 函数中,你声明了两个指针 La 和 Lb,但没有为它们分配内存。这会导致在访问它们时出现未定义行为,从而导致程序崩溃。你需要使用 malloc 或者 new 为这两个指针分配内存。另外,在使用完链表后,记得释放这些内存,以避免内存泄漏。以下是修改后的 main 函数示例:
int main(){
//创建链表头节点并初始化:
node La = (node)malloc(sizeof(len));
if(La == NULL){
printf("内存分配失败\n");
return 1;
}
La->data=0;
La->next=NULL;
node Lb = (node)malloc(sizeof(len));
if(Lb == NULL){
printf("内存分配失败\n");
free(La);
return 1;
}
Lb->data=0;
Lb->next=NULL;
//生成有序链表
OrderInput(La,com_up);
//OrderInput(Lb,com_up);
list_shower(La);
//list_shower(Lb);
//释放内存
free(La);
free(Lb);
return 0;
}
请注意,在使用 malloc 分配内存后,需要检查指针是否为 NULL,以确保内存分配成功。另外,记得在程序结束前释放这些内存,以免造成内存泄漏。