連結リストについての質問です
Posted: 2010年5月28日(金) 20:41
はじめて投票します
C言語の連結リストについてなのですが、
連結リストの要素を挿入するプログラムで
書いたプログラムが
typedef struct CELL{ //リストの構造体
struct CELL *next;
int value;
};
CELL *header; //先頭要素
int main (void){
int val,Num;
header=(CELL*)malloc(sizeof(CELL)); //メモリの確保
if(header==NULL) exit(1);
header->next=NULL;
header->value=0;
printf("追加するリストの値を入力してください ");
scanf("%d",&val); //追加要素の値
printf("リストの挿入する場所は何番目ですか? ");
scanf("%d",&Num); //追加する場所
insert(header,val,Num); //追加関数
putchar('\n');
showlist(header); //リストの表示
return 0;
}
//表示関数
void showlist(CELL *header){
CELL *x;
for(x=header;x!=NULL;x=x->next)
printf("%d\n",x->value);
free(x);
}
//リストへの追加関数
void insert(CELL *header, int val,int Num){
CELL *New; //挿入するリスト
int i;
New=(CELL*)malloc(sizeof(CELL));
if(New==NULL) exit(1);
if(Num==1){ //先頭に挿入するとき
New->value=val;
New->next=header;
header=New;
}else{ //先頭以外に挿入するとき
for(i=1;header->next!=NULL && i<Num;i++){ //挿入場所へのリストの移動
header=header->next;
}
New->value=val;
New->next=header->next;
header->next=New;
}
}
という感じに書いたのですが
先頭以外の挿入はうまくいくのですが、先頭への挿入がうまくいかないです
よければ、おしえてください
よろしくお願いします
C言語の連結リストについてなのですが、
連結リストの要素を挿入するプログラムで
書いたプログラムが
typedef struct CELL{ //リストの構造体
struct CELL *next;
int value;
};
CELL *header; //先頭要素
int main (void){
int val,Num;
header=(CELL*)malloc(sizeof(CELL)); //メモリの確保
if(header==NULL) exit(1);
header->next=NULL;
header->value=0;
printf("追加するリストの値を入力してください ");
scanf("%d",&val); //追加要素の値
printf("リストの挿入する場所は何番目ですか? ");
scanf("%d",&Num); //追加する場所
insert(header,val,Num); //追加関数
putchar('\n');
showlist(header); //リストの表示
return 0;
}
//表示関数
void showlist(CELL *header){
CELL *x;
for(x=header;x!=NULL;x=x->next)
printf("%d\n",x->value);
free(x);
}
//リストへの追加関数
void insert(CELL *header, int val,int Num){
CELL *New; //挿入するリスト
int i;
New=(CELL*)malloc(sizeof(CELL));
if(New==NULL) exit(1);
if(Num==1){ //先頭に挿入するとき
New->value=val;
New->next=header;
header=New;
}else{ //先頭以外に挿入するとき
for(i=1;header->next!=NULL && i<Num;i++){ //挿入場所へのリストの移動
header=header->next;
}
New->value=val;
New->next=header->next;
header->next=New;
}
}
という感じに書いたのですが
先頭以外の挿入はうまくいくのですが、先頭への挿入がうまくいかないです
よければ、おしえてください
よろしくお願いします