首页 > 解决方案 > 哈希表 C++ 的链表数组

问题描述

我正在尝试将哈希函数实现h(x) = x % 127为链表数组。目前我已经创建了一个添加函数,在其中将新节点添加到链表中,但是我不明白为什么任何链表中都没有写入任何内容。我正在从文件中读取输入编号,并将其作为 input%127 发送到链接列表。

#include<iostream>
#include<cstdlib>
#include<fstream>
//#define prim 127
using namespace std;

ifstream f("hashuri.in");
ofstream g("hashuri.out");

struct nod {
    int info;
    nod *next;
};

void add_nod(nod *p, nod *&u, int info) {
    if (p == NULL) {
        p = new nod;
        p->info = info;
        u = p;
        u->next = NULL;
    }
    else {
        nod *c = new nod;
        c->info = info;
        u->next = c;
        u = c;
        u->next = NULL;
    }
}

int main()
{
    int nr_op, op, x, prim = 127;
    nod * p[127], *u[127];
    for (int i = 0; i < prim; i++) {
        p[i] = u[i] = NULL;
    }

    f >> nr_op;
    while (!f.eof()) {
        f >> op >> x;
        if (op == 1) {
            //delete_nod(p[x%prim], u[x%prim], x);
        }
        if (op == 2) {
            add_nod(p[x%prim], u[x%prim], x);
        }
        if (op == 3) {
            //search_nod(p[x%prim], u[x%prim], x);
        }
    }

    //printing an array of linked lists
    for (int i = 0; i < prim; i++) {
        if (p[i] != NULL) {
            nod *c;
            c = p[i];
            cout << i << ": ";
            while (c != NULL) {
                cout << c->info << " ";
                c = c->next;
            }
        }
    }

    system("Pause");
    return 0;
}

我的输入文件permutari.in包含:

7
1 3
1 20
2 7
3 4
3 20
2 20
3 20

标签: c++hashlinked-list

解决方案


推荐阅读