关于我们

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻公共列表

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

发布时间:2023-06-26 14:00:24

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

class Solution  {  public:  vectorreversePrint(ListNode* head)  {  recur(head);  return res;  }  private:  vectorres;  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;  vectorv1 = obj.reversePrint(n1); //形参为指针时,传入的参数为地址  for (vector::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!


/template/Home/leiyu/PC/Static