[英]C++ Recursive Function
我是不久前剛學c++的學生。 我心里有一個疑問,對於下面的鏈表代碼,我不太明白它背后的邏輯,為什么函數在到達return時,會繼續執行func1()和cout命令? 是不是每當程序到達返回時,它會自動退出該功能並忽略下面的其余塊?
#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;
}
讓我們看看幕后發生了什么。 例子; 鏈表: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。
場景2:假設你先寫遞歸調用,然后print語句頭會先到達末尾,然后再打印。 所以輸出將是 CBA
void func1(Node* head) {
if (head == NULL)
{
return;
}
func1(head->next);
cout << " " << head->value;
}
為什么函數在到達返回時,會繼續執行 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
。
在程序中的某個點,有 4 次func1
調用“正在進行”,每個調用的head
參數值不同。
僅在最后一次調用中達到顯式return
。 然后繼續之前的調用,並到達結尾}
,這是一個隱式返回。
因為在遞歸調用之后什么也沒有發生,我們稱之為尾遞歸。 這種遞歸相當於一個循環。
void func1(Node* head) {
while (head != NULL)
{
std::cout << " " << head->value;
head = head->next;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.