4
4
#include "io.h"
5
5
#include "tree.h"
6
6
7
- /* addtree: add a node with w, at or below p */
8
- struct tnode * addtree (struct tnode * p , char * w ) {
7
+ /* addtree: add a node with w, line n, at or below p */
8
+ struct tnode * addtree (struct tnode * p , char * w , int n ) {
9
9
int cond ;
10
10
11
11
if (p == NULL ) { /* a new word has arrived */
12
12
p = talloc ();
13
13
p -> word = _strdup (w );
14
14
p -> count = 1 ;
15
15
p -> left = p -> right = NULL ;
16
- } else if ((cond = strcmp (w , p -> word )) == 0 )
16
+ p -> lsize = 0 ;
17
+ p -> lnum [p -> lsize ++ ] = n ;
18
+ } else if ((cond = strcmp (w , p -> word )) == 0 ) {
17
19
p -> count ++ ; /* repeated word */
20
+ if (lsearch (p -> lnum , n , p -> lsize ) < 0 )
21
+ p -> lnum [p -> lsize ++ ] = n ;
22
+ }
18
23
else if (cond < 0 )
19
- p -> left = addtree (p -> left , w );
24
+ p -> left = addtree (p -> left , w , n );
20
25
else
21
- p -> right = addtree (p -> right , w );
26
+ p -> right = addtree (p -> right , w , n );
22
27
return p ;
23
28
}
24
29
@@ -27,6 +32,8 @@ void treeprint(struct tnode *p) {
27
32
if (p != NULL ) {
28
33
treeprint (p -> left );
29
34
printf ("%4d %s\n" , p -> count , p -> word );
35
+ for (int i = 0 ; i < p -> lsize ; i ++ )
36
+ printf ("\t%4d\n" , p -> lnum [i ]);
30
37
treeprint (p -> right );
31
38
}
32
39
}
@@ -35,3 +42,12 @@ void treeprint(struct tnode *p) {
35
42
struct tnode * talloc (void ) {
36
43
return (struct tnode * ) malloc (sizeof (struct tnode ));
37
44
}
45
+
46
+ /* lsearch: linear search for ele in arr[0] ... arr[size] */
47
+ int lsearch (int * arr , int ele , int size ) {
48
+ for (int i = 0 ; i < size ; i ++ )
49
+ if (arr [i ] == ele )
50
+ return i ;
51
+ /* ele not found in arr */
52
+ return -1 ;
53
+ }
0 commit comments