Self-reference structure
Task: count the number of times all words appear in the input.
Two solutions:
<1> when reading any word in the input, place it in the correct position to ensure that all words are arranged in order.
<2> adopt a binary tree data structure
Each word is a node in the tree, and each node includes:
A pointer to the word content
Count the number of statistical occurrences
A pointer pointing to the left subtree
A pointer pointing to the right subtree
Any node can have up to two Subtrees, or only one or none of them.
Key point: all operations on a node must be ensured. The left subtree of any node only contains words that are less than the words in the node in the Lexicographic Order, the right subtree contains only the words whose Lexicographic Order is greater than the words in the node.
Standard library function malloc can meet alignment requirements
# Include <stdio. h> # include <string. h> # include <ctype. h> # define maxword 100 struct tnode {char * word; int count; struct tnode * left; struct tnode * Right ;}; struct tnode * addtree (struct tnode *, char *); void treeprint (struct tnode *); int getword (char *, INT); int main (void) {struct tnode * root; char word [maxword]; root = NULL; while (getword (word, maxword )! = EOF) if (isalpha (word [0]) root = addtree (root, word); treeprint (Root); Return 0;} struct tnode * talloc (void ); char * strdup1 (char *);/** addtree function: Add a W node */struct tnode * addtree (struct tnode * P, char * w) {int cond; If (P = NULL) {P = talloc (); P-> word = strdup1 (w); P-> COUNT = 1; p-> left = p-> right = NULL;} else if (cond = strcmp (W, p-> word) = 0) P-> count ++; else if (cond <0) P-> left = addtree (p-> Left, W); elsep-> right = addtree (p-> right, W); Return P;}/** treeprint function: print tree p */void treeprint (struct tnode * P) {If (P! = NULL) {treeprint (p-> left); printf ("% 4D % s \ n", p-> count, p-> word ); treeprint (p-> right) ;}}/** talloc function: Create a tnode */# include <stdlib. h> struct tnode * talloc (void) {return (struct tnode *) malloc (sizeof (struct tnode);}/** strdup function: copy the passed parameter string to a safe position */char * strdup1 (char * s) {char * P; P = (char *) malloc (strlen (s) + 1); If (P! = NULL) strcpy (P, S); Return P;} int GETID (void); void ungetch1 (INT);/** getword function: read the next word or character */INT getword (char * word, int Lim) from the input {int C; char * w = word; while (isspace (C = getspace (); If (C! = EOF) * w ++ = C; If (! Isalpha (c) {* w = '\ 0'; return C ;}for (; -- Lim> 0; W ++) if (! Isalnum (* w = getcounter () {// printf ("in the getword ()"); ungetcounter (* w); break ;} * w = '\ 0'; return word [0] ;}# define bufsize 1000 char Buf [bufsize]; int bufp = 0; int getch1 (void) {return (bufp> 0 )? Buf [-- bufp]: getchar ();} void ungetch1 (INT c) {If (bufp> = bufsize) printf ("ungetch: Too character characters \ n "); elsebuf [bufp ++] = C ;}