aboutsummaryrefslogtreecommitdiff
path: root/6.3/tree.c
blob: a83d294e9f3abe74e8cce1f1a8203282536a5112 (plain) (blame)
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <error.h>
#include <errno.h>
#include "tree.h"

struct tnode *talloc(void);
struct linklist *lalloc(void);
void lfree(struct linklist *p);
void addln(struct tnode *p, int linenum);

struct tnode *addtree(struct tnode *p, char *w, int linenum)
{
	int cond;

	if (p == NULL) {
		p = talloc();
		p->word = strdup(w);
		p->lines = lalloc();
		p->lines->linenum = linenum;
		p->lines->ptr = NULL;
		p->left = p->right = NULL;
	} else if (!(cond = strcasecmp(w, p->word))) {
		addln(p, linenum);
	} else if (cond < 0) {
		p->left = addtree(p->left, w, linenum);
	} else if (cond > 0) {
		p->right = addtree(p->right, w, linenum);
	}

	return p;
}

void addln(struct tnode *p, int linenum)
{
	struct linklist *temp;

	temp = p->lines;
	while (temp->ptr != NULL && temp->linenum != linenum)
		temp = temp->ptr;

	if (temp->linenum != linenum) {
		temp->ptr = lalloc();
		temp->ptr->linenum = linenum;
		temp->ptr->ptr = NULL;
	}
}

void tprint(struct tnode *p)
{
	struct linklist *temp;

	if (p != NULL) {
		tprint(p->left);

		printf("%10s: ", p->word);
		for (temp = p->lines; temp != NULL; temp = temp->ptr)
			printf("%4d", temp->linenum);
			// printf("%d%s", temp->linenum,
			// 	 (temp->ptr == NULL) ? "\n" : ", ");
		putchar('\n');
		tprint(p->right);
	}
}

void tfree(struct tnode *p)
{
	if (p != NULL) {
		tfree(p->left);
		tfree(p->right);
		lfree(p->lines);
		free(p->word);
		free(p);
	}
}

void lfree(struct linklist *p)
{
	if (p != NULL) {
		lfree(p->ptr);
		free(p);
	}
}

struct tnode *talloc(void)
{
	return (struct tnode *) malloc(sizeof(struct tnode));
}

struct linklist *lalloc(void)
{
	return (struct linklist *) malloc(sizeof(struct linklist));
}