我是不久前剛學c 的學生。我心里有一個疑問,對于下面的鏈表代碼,我不太明白它背后的邏輯,為什么函式在到達return時,會繼續執行func1()和cout命令?是不是每當程式到達 return 時,它會自動退出該函式并忽略下面的其余塊?
#include <iostream>
using namespace std;
// Creating a node
class Node {
public:
string value;
Node* next;
};
void func1(Node* head) {
if (head == NULL)
{
return;
}
cout << " " << head->value;
func1(head->next);
}
int main() {
Node* head;
Node* one = NULL;
Node* two = NULL;
Node* three = NULL;
// allocate 3 nodes in the heap
one = new Node();
two = new Node();
three = new Node();
// Assign value values
one->value = "A";
two->value = "B";
three->value = "C";
// Connect nodes
one->next = two;
two->next = three;
three->next = NULL;
func1(one);
return 0;
}
uj5u.com熱心網友回復:
讓我們看看幕后發生了什么。例子; 鏈表:head -> A -> B -> C -> NULL;
void func1(Node* head) {
if (head == NULL)
{
return;
}
cout << " " << head->value;
func1(head->next);
}
迭代 1: Head 不是 NULL,所以它列印 A,現在它遞回呼叫func1(head->next)。
迭代 2: Head 不是 NULL,所以它列印 B,現在它遞回呼叫func1(head->next)。
迭代 3: Head 不是 NULL,所以它列印 C,現在它遞回呼叫func1(head->next)。
迭代 4: Head 為 NULL,因此它從函式回傳,您得到的輸出為 AB C。
場景二: 假設你先寫遞回呼叫,然后print陳述句頭會先到達末尾,然后再列印。 所以輸出將是 CBA
void func1(Node* head) {
if (head == NULL)
{
return;
}
func1(head->next);
cout << " " << head->value;
}
uj5u.com熱心網友回復:
為什么函式在到達回傳時,會繼續執行 func1() 和 cout 命令?
只有當該if條件不滿足,命令func1()和cout將被執行。在另一方面,如果if條件滿足,return將執行,func1()并且cout將不會被執行。
查看以下示例以獲得更多說明:
#include <iostream>
void func()
{
std::cout<<5<<std::endl;
if(1> 0)
{
return ;
}
std::cout<<6<<std::endl;
}
int main()
{
func();
}
因為1是大于0,所述if條件被滿足,并且return將被執行,但是cout<<6;將不被執行。
現在在您的示例代碼中,您有
if (head == NULL)
這意味著只有當該head指標NULL的if將是滿足,return會被執行,但func1()并cout不會被執行。在另一方面,如果head指標不為NULL,則if不會滿意,所以return不會被執行,但func1()和cout將被執行。
uj5u.com熱心網友回復:
在您的程式中的某個點,有 4 個func1“正在進行”的head呼叫,每個呼叫的引數值不同。
return僅在最后一次呼叫中達到顯式。然后之前的呼叫繼續,并到達 end },這是一個隱式回傳。
因為在遞回呼叫之后什么也沒有發生,我們稱之為尾遞回。這種遞回相當于一個回圈。
void func1(Node* head) {
while (head != NULL)
{
std::cout << " " << head->value;
head = head->next;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/358035.html
上一篇:如何查找傳遞給函式的物件名稱
