复制的队列更改 打印临时队列后队列的头部指针指向空 队列

Copied queue changes Queue's head pointer points to null after printing temp Queue

本文关键字:队列 指针 头部 打印 复制      更新时间:2023-10-16

在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;
        }
    }
}

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

我所做的是将 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;
        }
    }
}