I'm trying to create a word ladder, by using a linked list as a dictionary of words, and a queue to hold the word to be changed.
In the while loop of the queue, it reaches the first word in the dictionary (the word "toon" and changed to "poon") and stops. How can I make it continue until it reaches the targeted word?
Here is the code:
#include <iostream>
#include <queue>
#include <stack>
#include <string>
using namespace std;
struct Node
{
string data;
Node* next;
};
void insert(string ele, Node*& head)
{
Node* newnode = new Node;
newnode->data = ele;
newnode->next = head;
head = newnode;
}
void del(string key, Node*& head)
{
Node* temp = head;
Node* prev = NULL;
if (temp != NULL && temp->data == key)
{
head = temp->next;
delete temp;
return;
}
else
{
while (temp != NULL && temp->data != key)
{
prev = temp;
temp = temp->next;
}
if (temp == NULL)
return;
prev->next = temp->next;
delete temp;
}
}
bool find(string key,Node *&head)
{
Node* p = head;
while (p != NULL)
{
if (p->data == key)
{
return true;
}
else
{
p = p->next;
}
}
if (p == NULL)
return false;
}
void print(Node*& head)
{
Node* p = head;
while (p != NULL)
{
cout << p->data;
p = p->next;
}
}
void WordLadder(string start, string target, Node*& head)
{
if (start == target)
cout << "They are the same";
if (find(target, head) != true)
cout << "Target Not found in dicionary";
//start word size
int wordlength = start.size();
//counter
int level = 0;
queue<string> q;
//push word in queue
q.push(start);
int len = 0;
while (!q.empty())
{
int wordlength = start.size();
int sizeofq = q.size();
string word = q.front();
q.pop();
for (int i = 0; i < wordlength ; i++)
{
for (char c = 'a'; c <= 'z'; c++)
{
word[i] = c;
if (word == target)
{
q.pop();
}
if (find(word, head) == true)
{
del(word, head);
q.push(word);
break;
}
}
}
}
cout << len;
}
int main()
{
Node* head = NULL;
insert("poon", head);
insert("plee", head);
insert("same", head);
insert("poie", head);
insert("plie", head);
insert("poin", head);
insert("plea", head);
string start = "toon";
string target = "plea";
WordLadder(start, target, head);
return 0;
}