-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path6.3.c
137 lines (124 loc) · 2.85 KB
/
6.3.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_WORD_LEN 1000
#define MAXLEN 1000
char getch();
void ungetch(char c);
int getword(char *word, int limit) {
char *w = word;
char c;
while (isspace((c = getch())) && c != '\n') {
}
if (c != EOF) {
*w = c;
w++;
}
if (!isalpha(c)) {
*w = '\0';
return c;
}
limit--;
while (limit > 0) {
c = getch();
if (isalnum(c)) {
*w = c;
w++;
} else {
ungetch(c);
break;
}
limit--;
}
*w = '\0';
return w[0];
}
struct linkedlist {
int line_num;
struct linkedlist *next;
};
struct t_node {
char *word;
struct linkedlist *lines;
struct t_node *left;
struct t_node *right;
};
struct linkedlist *malloc_linkedlist_node(int line_num) {
struct linkedlist *p = malloc(sizeof(struct linkedlist));
p->line_num = line_num;
p->next = NULL;
return p;
}
int found_in_list(struct linkedlist *l, int line_num) {
struct linkedlist *p = l;
while (p != NULL) {
if (p->line_num == line_num) {
return 1;
}
p = p->next;
}
return 0;
}
void add_to_linkedlist(struct linkedlist *l, int line_num) {
struct linkedlist *p = l;
while (p->next != NULL) {
p = p->next;
}
struct linkedlist *n = malloc_linkedlist_node(line_num);
p->next = n;
}
void print_tree(struct t_node *p) {
if (p != NULL) {
print_tree(p->left);
struct linkedlist *pl = p->lines;
printf("word = %s, line numbers = ", p->word);
while(pl != NULL) {
printf("%d ", pl->line_num);
pl = pl->next;
}
printf("\n");
print_tree(p->right);
}
}
char *mystrdup(char *s) {
char *p = malloc(strlen(s)+1);
strcpy(p, s);
return p;
}
struct t_node *add_node(struct t_node *p, char *w, int line_num) {
if (p == NULL) {
p = malloc(sizeof(struct t_node));
p->word = mystrdup(w);
p->lines = malloc_linkedlist_node(line_num);
p->left = NULL;
p->right =NULL;
} else {
int cond = strcmp(w, p->word);
if (cond > 0) {
p->right = add_node(p->right, w, line_num);
} else if (cond < 0) {
p->left = add_node(p->left, w, line_num);
} else {
if (!found_in_list(p->lines, line_num)) {
add_to_linkedlist(p->lines, line_num);
}
}
}
return p;
}
int main() {
int len;
char word[MAX_WORD_LEN];
struct t_node *root = NULL;
int line_num = 1;
int c;
while ((c = getword(word, MAX_WORD_LEN)) != EOF) {
if (c == '\n') {
line_num++;
continue;
}
root = add_node(root, word, line_num);
}
print_tree(root);
}