【发布时间】:2021-05-07 20:15:22
【问题描述】:
我正在尝试创建一个单词阶梯,使用链表作为单词字典,并使用队列来保存要更改的单词。
在队列的while循环中,它到达字典中的第一个单词(单词"toon"并更改为"poon")并停止。我怎样才能让它继续直到它到达目标单词?
代码如下:
#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;
}
【问题讨论】:
-
看起来您正在尝试使用与 BFS 非常相似的算法。您可以尝试搜索它是如何构建的。我会尝试修复您的代码。
-
您的代码看起来像是 C 和 C++ 的混合体。你确定一个。你应该重新实现一个链表(STL 中已经有
std::list,你正在使用它来表示std::string和std::queue),b。你为什么要使用像NULL、operator new和裸指针而不是智能指针和移动语义和c。你为什么首先使用链表?链表在现代机器上效率极低,与vector和deque之类的东西相比几乎毫无意义。此外,我会远离指针引用(即 T*&) - 事情会变得非常混乱。 -
如果有比链表更好的方法,请告诉我 - 如果你真的需要,请使用
std::vector或std::list一个链表(提示:你没有)。在没有充分理由的情况下重新发明轮子通常会导致代码质量较差,难以理解。 -
在这里,我建议使用一些具有良好“查找”功能的数据结构(尽管您可以保持
std::vector排序)。我会使用std::set -
List of and documentation for the containers offered out of the box by modern C++。阅读每一种的推荐用法,然后选择最适合这项工作的一种。但是,如果
std::vector在输入小数据集时甚至优于最佳拟合,请不要感到惊讶。算法越智能,通常在开始获得奖励之前要克服的开销就越多,vector是如此“愚蠢”,几乎是中小型数据量的王者。
标签: c++ linked-list queue