回答編集履歴
1
コード追加
test
CHANGED
@@ -1,2 +1,78 @@
|
|
1
1
|
node の前に入れるのであれば node の前の node が分からないといけないはずですが、該当箇所ではそれが分からないのではないでしょうか。
|
2
2
|
(そもそもバグがあるようにも見えますが。)
|
3
|
+
|
4
|
+
---
|
5
|
+
2行とか再帰とか元のコードに拘り(縛り?)が無ければ、以下で動作しました。
|
6
|
+
```c
|
7
|
+
#include <stdio.h>
|
8
|
+
#include <stdlib.h>
|
9
|
+
#include <string.h>
|
10
|
+
|
11
|
+
#define LEN 10
|
12
|
+
|
13
|
+
// 文字列1つとポインタの構造体
|
14
|
+
typedef struct node {
|
15
|
+
char str[LEN];
|
16
|
+
struct node* next;
|
17
|
+
} NODE;
|
18
|
+
|
19
|
+
// インサート関数
|
20
|
+
NODE* insert(char str[LEN], NODE* root) {
|
21
|
+
//printf("insert(%s,%p)\n", str, root);
|
22
|
+
NODE *p = (NODE*)malloc(sizeof(NODE));
|
23
|
+
strcpy(p->str, str);
|
24
|
+
p->next = NULL;
|
25
|
+
|
26
|
+
NODE dummy;
|
27
|
+
dummy.next = root;
|
28
|
+
NODE *prev = &dummy;
|
29
|
+
|
30
|
+
for( ; prev->next!=NULL; prev=prev->next) {
|
31
|
+
NODE *node = prev->next;
|
32
|
+
//printf("strcmp(%s,%s)=%d\n", str, node->str, strcmp(str, node->str));
|
33
|
+
if(strcmp(str, node->str) <= 0) {
|
34
|
+
p->next = node;
|
35
|
+
break;
|
36
|
+
}
|
37
|
+
}
|
38
|
+
|
39
|
+
prev->next = p;
|
40
|
+
return dummy.next;
|
41
|
+
}
|
42
|
+
|
43
|
+
void print(NODE *node) {
|
44
|
+
for( ; node!=NULL; node=node->next) {
|
45
|
+
printf("%s -> ", node->str);
|
46
|
+
}
|
47
|
+
printf("NULL\n");
|
48
|
+
}
|
49
|
+
|
50
|
+
int main(void) {
|
51
|
+
NODE *root = NULL;
|
52
|
+
print(root);
|
53
|
+
|
54
|
+
root = insert("123", root);
|
55
|
+
print(root);
|
56
|
+
|
57
|
+
root = insert("abc", root);
|
58
|
+
print(root);
|
59
|
+
|
60
|
+
root = insert("ABC", root);
|
61
|
+
print(root);
|
62
|
+
|
63
|
+
root = insert("0", root);
|
64
|
+
print(root);
|
65
|
+
|
66
|
+
root = insert("xyz", root);
|
67
|
+
print(root);
|
68
|
+
}
|
69
|
+
```
|
70
|
+
実行結果(piaza.io)
|
71
|
+
```plain
|
72
|
+
NULL
|
73
|
+
123 -> NULL
|
74
|
+
123 -> abc -> NULL
|
75
|
+
123 -> ABC -> abc -> NULL
|
76
|
+
0 -> 123 -> ABC -> abc -> NULL
|
77
|
+
0 -> 123 -> ABC -> abc -> xyz -> NULL
|
78
|
+
```
|