【发布时间】:2016-10-21 15:16:33
【问题描述】:
这是我做过的一个实验,就是用 C++ 创建一个简单的队列。
#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() 返回什么值?
-
打开你的编译器警告和/或停止忽略在你的
pop函数中告诉你“并非所有控制路径都返回值”的警告。那将是那里可能有问题的第一个线索。我希望“实验室讲师也不知道”,这实际上不是真的,他们确实知道但希望你自己找到它。如果没有,就拿他们给你的几乎所有东西来换取它的价值(可能不会太多)。 -
@NathanOliver 由于停止问题的不确定性,它确实如此。
-
@Quentin 我删除了评论,因为我意识到这里只提出了一个警告。我不认为这与停止问题有关,因为每个都检查是否所有退出路径都返回。
-
@NathanOliver 过于复杂。仅仅确定
foo() { bar(); }是否应该触发警告就需要知道bar是否停止。