# 資料結構(0321)程式碼 ### node_3.c ```c= #include <stdio.h> #include <stdlib.h> typedef struct node { int data; struct node *link; } LNODE; void insert_head(LNODE **, int); void show_list(LNODE *); int main() { LNODE *h = NULL; insert_head(&h, 10); show_list(h); insert_head(&h, 20); show_list(h); insert_head(&h, 30); show_list(h); return 0; } void insert_head(LNODE **a, int data) { LNODE *p; p = malloc(sizeof(LNODE)); p->data = data; p->link = NULL; if ((*a) == NULL) { (*a) = p; } else { p->link = (*a); (*a) = p; } } void show_list(LNODE *a) { while (a != NULL) { printf("%3d", a->data); a = a->link; } printf("\n"); } ``` ### node_4.c ```c= #include <stdio.h> #include <stdlib.h> typedef struct node { int data; struct node *link; } LNODE; void insert_tail(LNODE **, int); void show_list(LNODE *); int main() { LNODE *h = NULL; insert_tail(&h, 10); show_list(h); insert_tail(&h, 20); show_list(h); insert_tail(&h, 30); show_list(h); return 0; } void insert_tail(LNODE **a, int data) { LNODE *p; p = malloc(sizeof(LNODE)); p->data = data; p->link = NULL; if ((*a) == NULL) { (*a) = p; } else { LNODE *t = (*a); while (t->link != NULL) { t = t->link; } t->link = p; } } void show_list(LNODE *a) { while (a != NULL) { printf("%3d", a->data); a = a->link; } printf("\n"); } ``` ### node_5.c ```c= #include <stdio.h> #include <stdlib.h> typedef struct node { int data; struct node *link; } LNODE; void insert_middle(LNODE **, int); void show_list(LNODE *); int main() { LNODE *h = NULL; insert_middle(&h, 40); show_list(h); insert_middle(&h, 30); show_list(h); insert_middle(&h, 20); show_list(h); insert_middle(&h, 50); show_list(h); insert_middle(&h, 10); show_list(h); return 0; } void insert_middle(LNODE **a, int data) { LNODE *p; p = malloc(sizeof(LNODE)); p->data = data; p->link = NULL; if (((*a) == NULL) || (data < (*a)->data)) { p->link = (*a); (*a) = p; } else { LNODE *t = (*a); while (t != NULL) { if ((data >= t->data) && ((t->link == NULL) || (data < t->link->data))) { p->link = t->link; t->link = p; break; } t = t->link; } } } void show_list(LNODE *a) { while (a != NULL) { printf("%3d", a->data); a = a->link; } printf("\n"); } ```