Reverse反转算法

1 #include <iostream>
2 3 using namespace std;
4 //交换的函数 5 void replaced(int &a,int &b){
6 int t = a;
7 a = b;
8 b = t;
9 }
10 //反转 11 void reversed(int a[],int length){
12 int left = 0;
13 int right = length - 1;
14 while (left < right) {
15 replaced(a[left], a[right]);
16 left++;
17 right--;
18 }
19 }
20 void output(int a[],int length)
21 {
22 for (int i = 0; i<length; i++) {
23 cout << a[i] << " ";
24 }
25 }
26 int main()
27 {
28 int a[] = {1,2,3,4,5,6,7,8,9};
29 output(a, 9);
30 cout << endl;
31 reversed(a, 9);
32 output(a, 9);
33 }

斐波那契数列

1 #include <iostream>
2 3 using namespace std;
4 5 //斐波那契数列 6 int qiebona(int a)
7 {
8 //也可以用if语句 9 switch (a) {
10 case 1:
11 case 2:
12 return a;
13 break;
14 15 default:
16 return qiebona(a-1)+qiebona(a-2);
17 break;
18 }
19 }
20 int main()
21 {
22 //验证斐波那契函数 23 cout << qiebona(1) << endl;
24 //然后打印前n个数的斐波那契数列 25 for (int i = 1; i <= 10; i++) {
26 cout << qiebona(i) << " ";
27 }
28 return 0;
29 }

Reverse反转单链表算法

1 #include <iostream>
2 3 using namespace std;
4 //1首先这个数据节点中只有一个指针作为成员数据,所以这是一个单链表的节点结构 5 struct node{
6 int payload;
7 node* next;
8 };
9 //2对于一个长的单链表的操作,我们只能这个长链表的第一个节点或者说是第一个指针指向的节点开始操作 10 node* reversed(node* first){
11 //3如果链表为空或者只有一个,那就返回它自己呗 12 if (first->next == nullptr || first == nullptr) {
13 return first;
14 }//4如果有下一个实例,就
15 //5获取下一个实例 16 node* second = first -> next;
17 //这里就是递归, 18 node* new_head = reversed(second);
19 /*6 将下一个节点内部指针的方向反转,但是在反转之前,也要获取这下一个节点原来指向的下下个节点,也就是说,在这个操作之前,要在通过下一个节点获取下下一个节点.
20 假设在前一步加:node* third = second->next;但是这个简单的思路有局限性,当链表很长的时候,后面会重复这个获取下一个节点的过程,这样肯定是不明智的,因为链表的个数不确定,你就不知道要写多少代码,所以最好的办法就是通过递归重复执行前面相同的步骤(即算法)*/ 21 second -> next = first;
22 first -> next = nullptr;
23 return new_head;//7由于递归的特性,最后的return返回值会往前传递到最前面 24 }