【发布时间】:2011-08-30 14:04:51
【问题描述】:
这是一个使用 linked list 的 FIFO 程序。该程序没有提供所需的输出,但会生成一个长循环,该循环会在一段时间后停止,并且会显示程序已停止工作的消息。有什么问题?
#include <iostream>
using namespace std;
struct node {
int data;
struct node* previous; // This pointer keeps track of the address of the previous node
};
struct queue {
node* first;
node* last;
};
node* dataNode_P_A;
bool loop = true;
struct node* enterData();
struct node* enter_N_Data();
void displayQueue();
int main() {
struct node* dataNode= enterData();
while( loop ) {
cout << "Want to enqueue ? Press y/n : ";
char ans;
cin >> ans;
if( ans == 'y' ) {
struct node* dataNode_N = enter_N_Data();
} else {
break;
}
}
displayQueue();
}
struct node* enterData() {
cout << "Enter the number : ";
dataNode_P_A = new node; // Now dataNode points to a chunk allocated to node
cin >> dataNode_P_A->data;
dataNode_P_A->previous = NULL; // this is set to NULL because no one follows till now
queue* q = new queue;
q->first = dataNode_P_A; // this pointer points to the first element
return dataNode_P_A;
}
struct node* enter_N_Data() {
cout << endl << "Enter the number : ";
node* dataNode = new node;
cin >> dataNode->data;
dataNode->previous = dataNode_P_A;
queue* q = new queue;
q->last = dataNode; // this pointer points to the last element
return dataNode;
}
void displayQueue() {
while( dataNode_P_A != NULL ) {
cout << dataNode_P_A->data << endl;
dataNode_P_A++;
}
}
【问题讨论】:
-
从未见过只有指向前一个节点的指针的链表。 N
-
嗯,奇怪。通常你会跟踪单链表中的下一个节点,而不是前一个......
-
期望的输出是什么? 实际输出是什么?它究竟在哪里停止工作?是时候启动你的调试器了。
-
@TonyTheTiger:这是一个标准的单链表。是“下一个”还是“上一个”是任意的。
-
对于 OP,先停止写 C。
标签: c++ visual-c++ data-structures queue fifo