我正在反转一个双向链表。我的功能是:
Node* Reverse(Node* head)
{
// Complete this function
// Do not write the main method.
Node* temp = new Node();
if ( head == NULL) { return head; }
while ( head != NULL) {
temp = head->next;
head->next = head->prev;
head->prev = temp;
if (temp == NULL ) { break; }
head = temp;
}
return head;
}
这工作正常。 如果我不使用 break 命令,如果我执行“return head”而不是函数退出 while 循环并出现编译错误:控制到达非 void 函数的末尾 [-Werror=return-type]
Node* Reverse(Node* head)
{
// Complete this function
// Do not write the main method.
Node* temp = new Node();
if ( head == NULL) { return head; }
while ( head != NULL) {
temp = head->next;
head->next = head->prev;
head->prev = temp;
if (temp == NULL ) { return head; }
head = temp;
}
}
这背后的原因可能是什么?
最佳答案
原因是编译器不知道 temp
总会在某个时刻以 NULL
结束,它只知道循环可以结束,函数将没有返回语句。
正如 CompuChip 所指出的,您可以在末尾添加以下行,以安抚编译器:
throw std::runtime_error("Control should never reach this point");
或者您可以在最后简单地返回 NULL
。
关于c++ - 返回 C++ 中断循环的内部循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35335645/