/* 連結リストを表示する */ #include <stdio.h> #include <stdlib.h> typedef struct node{ int data; struct node *next; } NODE, *Nodep; void displist(Nodep p); Nodep firstp; /* 先頭ノードを指すポインタ */ main() { /* [1, 5, 9] というリストを作成 */ firstp = (Nodep)malloc(sizeof(NODE)); firstp->data = 1; firstp->next = (Nodep)malloc(sizeof(NODE)); firstp->next->data = 5; firstp->next->next = (Nodep)malloc(sizeof(NODE)); firstp->next->next->data = 9; firstp->next->next->next = NULL; displist(firstp); } void displist(Nodep p) { printf("List"); if( p == NULL ) { printf(" is empty\n"); return; } do { printf("%5d", p->data ); p = p->next; } while(p); printf("\n"); } /* end of llist1.c */
/* 連結リストを表示する */ #include <stdio.h> #include <stdlib.h> typedef struct node{ int data; struct node *next; } NODE, *Nodep; void displist(Nodep fp); NODE first; /* 先頭ノードを指すポインタを含むノード */ main() { /* [1, 5, 9] というリストを作成 */ first.next = (Nodep)malloc(sizeof(NODE)); first.next->data = 1; first.next->next = (Nodep)malloc(sizeof(NODE)); first.next->next->data = 5; first.next->next->next = (Nodep)malloc(sizeof(NODE)); first.next->next->next->data = 9; first.next->next->next->next = NULL; displist(&first); } void displist(Nodep fp) { printf("List"); if( fp->next == NULL ) { printf(" is empty\n"); return; } for( fp = fp->next ; fp != NULL; fp = fp->next ) { printf("%5d", fp->data ); } printf("\n"); } /* end of llist2.c */
/* リストの先頭要素を削除する */ #include <stdio.h> #include <stdlib.h> typedef struct node{ int data; struct node *next; } NODE, *Nodep; void displist(Nodep fp); void delhead(Nodep fp); NODE first; /* 先頭ノードを指すポインタを含むノード */ main() { /* [1, 5, 9] というリストを作成 */ first.next = (Nodep)malloc(sizeof(NODE)); first.next->data = 1; first.next->next = (Nodep)malloc(sizeof(NODE)); first.next->next->data = 5; first.next->next->next = (Nodep)malloc(sizeof(NODE)); first.next->next->next->data = 9; first.next->next->next->next = NULL; displist(&first); delhead(&first); /* [5, 9] というリストになっているはず */ displist(&first); } void displist(Nodep fp) { printf("List"); if( fp->next == NULL ) { printf(" is empty\n"); return; } for( fp = fp->next ; fp != NULL; fp = fp->next ) { printf("%5d", fp->data ); } printf("\n"); } void delhead(Nodep fp) { Nodep p; if( p = fp->next ) { fp->next = fp->next->next; free(p); } } /* end of llist3.c */