【C++】递归调用——难点揭秘

        在函数递归调用这一块,很多小伙伴都容易犯迷糊,其实只要关键的一句理解了,那就 noproblem ,today 拿力扣上的一个数据结构题说一下!

class Solution 
 {
 public:
     vector<int> reversePrint(ListNode* head) 
     {
         recur(head);
         return res;
     }
 private:
     vector<int> res;
     void recur(ListNode* head) 
     {
         if (head == nullptr) 
             return;
         recur(head->next);
         res.push_back(head->val);
     }
 };

int main()
{
    //创建链表
	ListNode *n1 = new ListNode(1);						 // 节点 head
	ListNode *n2 = new ListNode(3);
	ListNode *n3 = new ListNode(2);

	//  需要构建引用指向
	n1->next = n2;
	n2->next = n3;

	Solution obj;
	vector<int> v1 = obj.reversePrint(n1);				 //形参为指针时,传入的参数为地址
	for (vector<int>::iterator it = v1.begin(); it != v1.end(); it++)
	{
		cout << *it << ' ';
	}
	cout << endl;

	system("pause");
	return 0;
}


输出结果:2 3 1

        关键句也即是第15行,recur(head->next); 只有输入的 head->next 节点为空时,该句执行结束后,才会执行同一等级中的下一条语句(res.push_back(head->val);),然后逐层回溯。只要此处理解了,所谓递归调用也是 so easy!

猜你喜欢

转载自blog.csdn.net/weixin_47156401/article/details/119881802
今日推荐