U E D R , A S I H C RSS

String OfCPlus Plus/세연

프로그래밍을 하며

심화문제를 트리루 짤려구 하는데 잘안되네.......
역시 포인터는 헷갈려, 분명 사소한데서 잘못되구 있는게 분명한데.......언넝 에러를 잡아야할텐에......

소스

~cpp 

#include <iostream>
using namespace std;
#include <fstream>

struct node{
	node * left_child;
	char data_word[30];
	node * right_child;
};

class SearchWord
{
private:
	node * head;
	node * temphead;
	int count;
public:
	SearchWord();
	void ReadWord();
	node * Search(char *, node *);
	void InsertWord(char *, node *);
	void Display(node *);
};

SearchWord::SearchWord()
{
	count = 0;
}

//파일에 있는 단어를 읽어온다
void SearchWord::ReadWord()
{
	ifstream file;
	char line[300];
	char * word = NULL;
		
	file.open("test.txt");
	while(!file.eof())
	{
		file.getline(line, 300);
		cout << line << "\n";
		word = strtok(line, " .");
		count ++;
		//단어가 트리에 있는지 검사
		temphead = head;		
		temphead = Search(word, temphead);
		//단어가 트리에 없으면 단어를 트리에 삽입
		if(temphead == NULL)
		{
			temphead = head;
			InsertWord(word, temphead);
		}
		//단어가 트리에 있으면 
		else
		{
		}
		while(word)
		{
			cout << word << "\n";
			word = strtok(0, " .");
			count++;
			//단어가 트리에 있는지 검사
			temphead = head;		
			temphead = Search(word, temphead);
			//단어가 트리에 없으면 단어를 트리에 삽입
			if(temphead == NULL)
			{
				temphead = head;
				InsertWord(word, temphead);
			}
			//단어가 트리에 있으면 
			else
			{
			}
		}
	}
	cout << "count : " << count << "\n";
}

//단어가 트리에 있으면 현재 노드반환, 없으면 NULL반환
node * SearchWord::Search(char * word, node * root)
{
	if(!root) return NULL;
	if(!strcmp(word, root->data_word)) return root;
	if(strcmp(word, root->data_word) < 0) return Search(word, root->left_child);
	return Search(word, root->right_child);
}

void SearchWord::InsertWord(char * word, node * root)
{
	if(!root)
	{
		head = new node;
		strcpy(head->data_word, word);
		head->left_child = head->right_child = NULL;
	}
	else
	{
		while(root != NULL)
		{
			if(strcmp(word, root->data_word) < 0)
				root = root->left_child;
			else
				root = root->right_child;			
		}
		node * temp = new node;
		strcpy(temp->data_word, word);
		temp->left_child = temp->right_child = NULL;
		root = temp;
	}
}

void SearchWord::Display(node * tree)
{
	cout << tree->data_word << "\n";
}




int main()
{
	SearchWord word;

	SearchWord();
	word.ReadWord();

	return 0;
}
Valid XHTML 1.0! Valid CSS! powered by MoniWiki
last modified 2021-02-07 05:28:07
Processing time 0.0124 sec