Posted on 2007-08-19 15:16
花之剑 阅读(450)
评论(0) 编辑 收藏 所属分类:
c/c++ & algorithm
1
2
#
include <stdio.h>
3
#
include<stdlib.h>
4
#
include<ctype.h>
5
#
include<string.h>
6
#
define MAXLEN 100
7
struct tnode
8
{
9
char
*
word;
10
int
count
;
11
struct tnode
*
left;
12
struct tnode
*
right;
13
}q;
14
int getword( char
*,
int);
15
struct tnode
*
addtree(struct tnode
*,
char
*
word);
16
char
*
strduup(char
*
s);
17
int getword(char
*
word
,
int limit)
18
{
19
int i;
/*
0表示为是词外,1表示在词内
*/
20
char c;
21
char
*
w
=
word;
22
while
(isspace(c
=
getchar()));
23
if
(c
!=
EOF)
24
*
word
++
=
c;
25
if
(
!
isalpha(c)) {
26
*
word
=
'
\0
'
;
27
return
c ;
28
}
29
30
for
(i
=
0
;(c
=
getchar())
!=
EOF
&&
i
<
limit;i
++
)
31
{
32
if
(
!
isalnum(
*
word
++=
c))
33
{
34
break
;
35
}
36
}
37
*
word
=
'
\0
'
;
38
return
w[
0
];
39
}
40
struct tnode
*
addtree(struct tnode
*
p
,
char
*
word)
41
{
42
int cond;
43
if
(p
==
NULL
)
44
{
45
p
=
(struct tnode
*
) malloc(
sizeof
(q));
46
p
->
word
=
strduup(word);
47
p
->
left
=
p
->
right
=
NULL
;
48
p
->
count
=
1
;
49
}
else
if
((cond
=
strcmp
(word
,
p
->
word))
==
0
)
50
{
51
p
->
count
++
;
52
}
else
if
(cond
<
0
)
53
{
54
p
->
left
=
addtree(p
->
left
,
word);
55
}
else
56
p
->
right
=
addtree(p
->
right
,
word);
57
return
p;
58
59
}
60
61
char
*
strduup(char
*
s)
/*
make a duplicate of s
*/
62
{
63
char
*
p;
64
p
=
(char
*
) malloc(
strlen
(s)
+
1
);
/*
+1 for '\0'
*/
65
if
(p
!=
NULL
)
66
strcpy(p
,
s);
67
return
p;
68
}
69
70
/*
treeprint: in-order print of tree p
*/
71
void treeprint(struct tnode
*
p)
72
{
73
if
(p
!=
NULL
) {
74
treeprint(p
->
left);
75
printf
(
"
%4d %s\n
"
,
p
->
count
,
p
->
word);
76
treeprint(p
->
right);
77
}
78
}
79
int main(int argc
,
char
*
argv[])
80
{
81
char word[MAXLEN];
82
struct tnode
*
root;
83
root
=
NULL
;
84
while
(getword(word
,
MAXLEN)
!=
EOF)
85
{
86
root
=
addtree(root
,
word);
87
}
88
treeprint(root);
89
return
0
;
90
}
91
92
93