データのイメージは図7のとおりである.リストの先頭はheadを用いて表して いる.最後のノードは次のノードが無いため,NULLポインターをいれている.
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 typedef struct seqn_tag{ // ノードを表す構造体
5 int data;
6 struct seqn_tag *next;
7 }seqn;
8
9 void insert(seqn *head, int n, int new_num);
10 void delete(seqn *head, int n);
11 void prt_node(seqn *head);
12
13 //============= メイン関数 =====================
14 int main(void)
15 {
16 seqn head;
17
18 head.next=NULL;
19
20 insert(&head, 0, 63);
21 insert(&head, 1, 27);
22 insert(&head, 2, 82);
23 insert(&head, 3, 79);
24 insert(&head, 4, 12);
25 prt_node(&head);
26
27 insert(&head, 1, 99);
28 prt_node(&head);
29
30 delete(&head, 1);
31 prt_node(&head);
32
33 return 0;
34 }
35
36 //============= 挿入 =====================
37 void insert(seqn *head, int n, int new_num)
38 {
39 int i=0;
40 seqn *p, *new_node;
41
42 new_node = (seqn *)malloc(sizeof(seqn));
43
44 new_node->data = new_num;
45
46 p=head;
47
48 while(i<n){
49 i++;
50 p=p->next;
51 if(p->next == NULL)break;
52 };
53
54 new_node->next = p->next;
55 p->next = new_node;
56 }
57
58 //============= 削除 =====================
59 void delete(seqn *head, int n)
60 {
61 int i=0;
62 seqn *p, *del_node;
63
64 p=head;
65 if(p->next == NULL)return;
66
67 while(i<n){
68 i++;
69 p=p->next;
70 if(p->next == NULL)break;
71 };
72
73 del_node=p->next;
74 p->next = del_node->next;
75 free(del_node);
76 }
77
78 //============= 表示 =====================
79 void prt_node(seqn *head)
80 {
81 seqn *p;
82
83 p=head;
84
85 if(p->next == NULL)return;
86
87 do{
88 p=p->next;
89 printf("%d,",p->data);
90 }while(p->next != NULL);
91
92 printf("\n");
93 }
63,27,82,79,12, 63,99,27,82,79,12, 63,27,82,79,12,