我的程序应该从命令行获取一个文件,该文件包含一个名称列表(不超过十个字符),后跟一个空格,然后是年龄,所有内容均以换行符分隔。我要创建一个大小为 10 的哈希表,使用单独的链接,哈希函数 h(x) = x mod 10,然后在完成后打印出该表。我快要得到我想要的东西了,但我不完全确定问题或解决方案。
代码:
#include <iostream>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <ctype.h>
#include <stdio.h>
using namespace std;
struct node
{
char name[10];
int age;
node *next;
node()
{
memset(name, 0x0, sizeof(name));
age = 0;
next = NULL;
}
};
int main(int argc, char *argv[])
{
node **heads = new node*[10];
for (int h = 0; h < 10; h++)
heads[h] = NULL;
string currentLine;
char c;
int index = 0, fileAge, hashValue = 0;
node *current;
ifstream input(argv[1]);
if (input.is_open()) //while file is open
{
while (getline(input, currentLine)) //checks every line
{
current = new node();
istringstream iss(currentLine);
while (iss >> c)
{
if (iss.eof())
break;
if (isdigit(c))
{
current->name[index] = 0;
iss.putback(c);
iss >> fileAge;
hashValue = fileAge % 10;
current->age = fileAge;
}
else
{
current->name[index] = c;
index++;
}
}
if ((&heads[hashValue]) == NULL)
heads[hashValue] = current;
else
{
current->next = heads[hashValue];
heads[hashValue] = current;
}
}
}
for (int x = 0; x < 10; x++)
{
printf(" Index %d: ", x);
node *currentNode = heads[x];
while (currentNode != NULL && !string(currentNode->name).empty())
{
printf("%s (%d), ", currentNode->name, currentNode->age);
currentNode = currentNode->next;
}
printf("\b\b\n");
}
输入:
Alice 77
John 68
Bob 57
Carlos 77
预期输出:
...
Index 7: Alice (77), Bob (57), Carlos (77)
Index 8: John (68)
Index 9:
...
实际输出:
...
Index 7:
Index 8:
Index 9:
...
我认为我的遍历以及我如何设置“下一个”节点存在问题,但我不确定这将如何导致 John 被打印两次并 Bob 被删除。感谢您的帮助。
最佳答案
我可以立即看到几件事:
您的
heads
数组是一个节点数组,但它应该是一个指向节点的指针数组:node **heads = new node *[10];
(不要忘记将所有指针初始化为
NULL
)。如果您要向已有元素的列表添加内容,您最终会调用
new node
两次(一次用于current
和一次用于next
)。那是不对的。您只添加了一个节点。
关于c++ - 在 C++ 中正确地进行单独链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26834138/