做的是一個帶有頭結點的單鏈表,思路是先在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改一下就不出錯了,這是為什麼呢?
求大神解答,剛入門,輕噴- -
謝謝!
幫你又改了一下:
#include <stdio.h>
#include <malloc.h>
#define ElemType int
#define OVERFLOW 0
#define OK 1
typedef struct node
{
ElemType data;
struct node *next;
}list;
list* 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 head;
}
void insert(list *head)
{
list *t,*m,*n;
//m和n表示相鄰的兩個節點,用於與節點比較大小,然後插入
int x;
scanf("%d",&x);
while(x!=0)
{
t=(list*)malloc(sizeof(list));
if(!t)
return;
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)
{
//你這裡注意先判斷一下就好了
if (m->next==NULL)
break;
m = m->next;
n = n->next;
if(t->data<=m->data)
{
n->next = t;
t->next = m;
break;
}
}
/* if(m->next==NULL)
m->next=t;*/
if(m->data<t->data)
m->next = t;
}
scanf("%d",&x);
}
}
void output(list *head)
{
list *p;
p=head->next;
while (p)
{
printf("%d ",p->data);
p=p->next;
}
}
int main(void)
{
//創建一個有頭結點的鏈表
printf("create a list");
list *head = NULL;
head = create(head);
insert(head);
output(head);
return 0;
}