【问题标题】:Copied queue changes Queue's head pointer points to null after printing temp Queue复制的队列在打印临时队列后更改队列的头指针指向空
【发布时间】:2018-03-21 23:02:25
【问题描述】:

dumpStack 结束后,对 printTable 的调用会完美打印每个索引中包含队列的 hashTable。当我之后尝试单独打印它时,head->next 指向 null(head 指向一个虚拟节点)。如何在不更改主队列指针的情况下打印临时队列?我不允许使用向量。

void dumpStack(listNode *top, int currentDigit, int currentTable) {
    while (isEmpty() == 0) {
        listNode *temp = pop();
        int digit = getDigit(temp, currentDigit);
        int hashIndex = digit;
        addTail(hashTable[currentTable][hashIndex], temp);
        cout << "Added " << temp->data << " to hashTable[" << currentTable << "][" << hashIndex << "]" << endl;
        cout << hashTable[currentTable][hashIndex]->head->next->data << endl;
    }
    cout << "DONE DUMPSTACK" << endl;
    printTable(hashTable[currentTable]);
    cout << hashTable[currentTable][9]->head->next->data << endl;
}

void printTable(linkedListQueue **ht) {
    for (int i = 0; i < 10; i++) {
        linkedListQueue *temp = ht[i];
        if (isEmpty(temp) == 0) {
            cout << "Table [" << currentTable << "][" << i << "]:";
            while (temp->head->next != nullptr) {
                cout << " " << temp->head->next->data;
                if (temp->head->next->next != nullptr)
                    cout << ",";
                temp->head->next = temp->head->next->next;
            }
            cout << endl;
        }
    }
}

我的代码的所有部分都是正确的,并且没有任何运行时错误。

【问题讨论】:

  • 当在 while not empty 循环中看到一个弹出函数时,我希望最后一个空容器。我们可以有一个minimal reproducible example 吗?旁注:这里使用了很多意想不到的指针。示例:top 是做什么用的?
  • dumpStack 所做的是将堆栈放入队列中。将整个堆栈转储到一个队列后,它会打印 hashTable 中的每个队列(总共 10 个队列)。因此,如果我在队列中有数字 19 和 9,它将进入 hashTable[9]。我使用临时指针来引用 hashTable[9] 中的队列并使用临时变量进行迭代。不知道为什么主队列也会改变。

标签: c++ list queue hashtable


【解决方案1】:

我所做的是将 listLinkedQueue *temp 更改为 listNode *temp 并让 temp 等于 head->next,因为 head 在我的代码中表示一个虚拟节点。这样,当我遍历队列时,我永远不会更改队列的原始顺序。

void printTable(linkedListQueue **ht) {
    for (int i = 0; i < 10; i++) {
        listNode *temp = ht[i]->head->next;
        if (temp != nullptr) {
            cout << "Table [" << currentTable << "][" << i << "]:";
            while (temp != nullptr) {
                cout << " " << temp->data;
                if (temp->next != nullptr)
                    cout << ",";
                temp = temp->next;
            }
            cout << endl;
        }
    }
}

【讨论】:

    猜你喜欢
    • 2018-04-30
    • 1970-01-01
    • 1970-01-01
    • 2013-05-21
    • 2015-07-13
    • 1970-01-01
    • 1970-01-01
    • 2021-04-09
    • 1970-01-01
    相关资源
    最近更新 更多