1、题目描述
C++代码
//
// Created by YaMiwan on 2020-05-05.
//
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
void compute_sum(int i, int &sum){ // 引用作为函数参数
if (i > 3){
return;
}
sum += i;
compute_sum(1 + i, sum);
}
int main(){
int sum = 0;
compute_sum(1, sum);
cout<<sum<<endl;
return 0;
}
输出
6
2、题目描述
将链表添加到数组中。
C++代码
//
// Created by YaMiwan on 2020-05-05.
//
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
void add_to_vec(ListNode *head, vector<int> &vec) { // 引用作为函数参数
if (!head){
return;
}
vec.push_back(head->val);
add_to_vec(head->next, vec);
}
int main() {
ListNode a(1);
ListNode b(2);
ListNode c(3);
ListNode d(4);
ListNode e(5);
a.next = &b;
b.next = &c;
c.next = &d;
d.next = &e;
vector<int> vec;
add_to_vec(&a, vec);
for (int i = 0; i < vec.size(); i++) {
cout << vec[i] << endl;
}
return 0;
}
输出
1
2
3
4
5