这是我已经完成的一个实验,它是使用C++创建一个简单的队列。Cout给出了一个奇怪的输出
#include "Task5.h"
#include <iostream>
using namespace std;
void push(const long &i, node* &n) {
if (n == NULL) {
node *ptr = new node;
ptr -> item = i;
ptr -> next = NULL;
n = ptr;
cout << "Created New Node." << endl;
}
else {
node *ptr = n;
cout << "Created Pointer" << endl;
while (ptr -> next != NULL){
cout << "Finding Next..." << endl;
ptr = ptr -> next;
}
cout << "I'm here." << endl;
node *temp = new node;
temp -> item = i;
ptr -> next = temp;
cout << "Node Created." << endl;
}
}
long pop(node* &n) {
if (n == NULL) cout << "HEY!!! Can't pop an empty queue." << endl;
else {
long val;
node *ptr = n;
n = n -> next;
val = ptr -> item;
delete ptr;
return val;
}
}
int main() {
node *head = NULL;
push(13,head);
push(10,head);
push(18,head);
push(22,head);
cout << pop(head) << endl;
cout << pop(head) << endl;
cout << pop(head) << endl;
cout << pop(head) << endl;
cout << pop(head) << endl;
cout << pop(head) << endl;
}
这给出以下输出:
Created New Node. Created Pointer I'm Here. Node Created. Created Pointer Finding Next... I'm here. Node Created. Created Pointer Finding Next... Finding Next... I'm here. Node Created. 13 10 18 22 HEY!!! Can't pop an empty queue. 6296192 HEY!!! Can't pop an empty queue. 6296192
所以最终结果是,代码工作,但它输出6296192随机。我想也许我拼错了一些东西或者cout正在转换endl;到十六进制。我的实验室教官也不知道发生了什么。有人能告诉我发生了什么事吗?如果有帮助,我通过Linux运行终端运行此代码。
在此先感谢。
问:当您尝试弹出空队列时,pop()返回什么值? – Mat
打开编译器警告和/或停止忽略警告,告诉您在“pop”函数中出现“并非所有控制路径都返回值”的效果。那将是第一个可能出现错误的线索。我希望“实验室老师也不知道”,实际上并不真实,他们*知道,但希望你自己找到它。如果没有,几乎所有他们给你的东西是值得的(这可能不会太多)。 – WhozCraig
@NathanOliver凭借停止问题的不确定性,它的确如此。 – Quentin