例)
struct CELL{
int value;
struct CELL *next;
}
メンバnext:次の要素を指すポインタ。最後の場合はメンバnextにNULLポインタをセット
struct CELL *p,*header;
if((p = malloc(sizeof(struct CELL))) == NULL){
fprintf(stderr,"Cannot allocate memory");
}
if((header = malloc(sizeof(struct CELL))) == NULL){
fprintf(stderr,"Cannot allocate memory");
}
for(p = header->next;p != NULL;p = p->next){
printf("%d\n",p->value);
}
ポインタxで指されているセルの次に、ポインタpで指されている新しいセルを挿入
p->next = x->next; x->next = p;
ポインタxで指されているセルの次のセルを削除
p = x->next; x->next = p->next;
先頭、末尾の要素、連結リストが空の時の処理が境界条件
struct CELL{
int value;
struct CELL *next;
}header;
insert(int a){
struct CELL *current_Cell,*prev_Cell,*new_Cell;
current_Cell = header.next;
prev_Cell = &header;
while(current_Cell != NULL && a > current_Cell->value){
prev_Cell = current_Cell;
current_Cell = prev_Cell->next;
}
if((new_Cell = malloc(sizeof(struct CELL)) == NULL){
fprintf(stderr,"Cannot allocate memory");
}
new_Cell->next = current_Cell;
new_Cell->value = a;
prev_Cell->next = new_Cell;
}
参考文献