做的是一个带有头结点的单链表,思路是先在main中定义头结点,然后在create函数中构造首元结点,接着在insert函数中判断输出是否结束(以$作为结束标志)。
#include <stdio.h>
#include <malloc.h>
#define ElemType int
#define OVERFLOW 0
#define OK 1
typedef struct node{
ElemType data;
struct node *next;
}list;
int create(list *head){
list *t;
t=(list*)malloc(sizeof(list));
if(!t){
printf("\n分配空间失败!");
return (OVERFLOW);
}
head = t;
int x;
printf("\nenter a number(end with $):");
scanf("%d",&x);
if(x!='$'){
t=(list*)malloc(sizeof(list));
t->data = x;
t->next = NULL;
head->next = t;
}
return OK;
}
int insert(list *head){
list *t,*m,*n;//m和n表示相邻的两个节点,用于与节点比较大小,然后插入
int x;
scanf("%d",&x);
while(x!='$'){
t=(list*)malloc(sizeof(list));
if(!t) return(OVERFLOW);
t->data = x;
t->next = NULL;
m = head->next;//这里调试出现错误
n = head;
if(t->data <= m->data){
n->next = t;
t->next = m;
}
else{
while(1){
m = m->next;
n = n->next;
if(t->data<=m->data){
n->next = t;
t->next = m;
break;
}
if(m->next==NULL) break;
}
if(m->next==NULL)
m->next = t;
}
scanf("%d",x);
}
return (OK);
}
int main(void){
//创建一个有头结点的链表
printf("create a list");
int i;
list *head = NULL;
i = create(head);
if(i) insert(head);
return 0;
}
然后我把create的返回值类型改成list*,返回head,然后再把main改一下就不出错了,这是为什么呢?
求大神解答,刚入门,轻喷- -
谢谢!