Friday, June 15, 2012

Discuss and implement phone book

In this post, I will discuss how to design data structure for a phone book and then implement the same.
A phone book, or some times called the contacts book is a collection of people information on the phone or any other device. So, for the purpose of simplicity, I will use the phone book as a collection of a set {Name, phone number, email} where any of them can be empty. The fastest implementation I found is using TRIE. So, I decided to implement the same.  Following is the implementation, which is pretty straight forward and self explanatory:


// This shows TRIE data structure implementation in C++
// The TRIE is implemented using two different classes.
// 1. Class for each node - this contains a vector of pointers to the same class and a character value
// 2. The container class that holds the root of the TRIE.

#include <iostream>
#include <string>
#include <vector>

using namespace std;

class Node
{
public:
Node() { c = ' ';}
~Node();
inline vector <Node *> GetChildren() { return child; }
Node *FindChild(char);
void AddChild(char);

private:
vector <Node *> child;
char c;
};

class TrieRoot
{
public:
void AddWord(string s);
bool IsWordPresent(string s);
TrieRoot() { node = new Node(); }
~TrieRoot() { delete node; }

private:
Node *node;
};

Node * Node::FindChild(char c)
{
if (child.empty()) return NULL;
for (unsigned int i = 0; i < child.size(); i++)
{
if ( child[i]->c == c ) 
return child[i];
}
return NULL;
}

void Node::AddChild(char c)
{
Node *temp = new Node();
temp->c = c;
child.push_back(temp);
}

void TrieRoot::AddWord (string s)
{
if (s.empty()) return;
Node *temp = node;
for(unsigned int i = 0; i < s.size(); i++)
{
Node *temp1 = temp->FindChild(s[i]);
if (temp1 == NULL)
{
temp->AddChild(s[i]);
temp = temp->FindChild(s[i]);
}
else
{
temp = temp1;
}
}

return;
}

// Breadth first search
bool TrieRoot::IsWordPresent(string s)
{
if (s.empty()) return false;
Node *temp = node;
for (unsigned int i = 0; i < s.size(); i++)
{
Node *temp1 = temp->FindChild(s[i]);
cout << "Charater to search for: " << s[i] << endl;
if (temp1 == NULL
return false;
}
temp = temp1;
}

return true;
}

Node::~Node()
{
if (!child.empty())
for (unsigned int i = 0; i < child.size(); i++)
delete child[i];
}

1 comment: