用递归方式完成以下程序
#include <iostream>
#include <windows.h>
using namespace std;
1.求前N个自然数之和
int sum(int N)
{
if(N == 1)
return 1;
return sum(N - 1) + N;
}
void FunTest()
{
int ret = sum(5);
cout<<"sum = "<<ret<<endl;
}
2.求N的阶乘 N!
int factorial(int N)
{
if(N == 1)
return 1;
return factorial(N - 1) * N;
}
void FunTest()
{
int ret = factorial(5);
cout<<"factorial = "<<ret<<endl;
}
3.逆序打印单链表
struct Node
{
Node(int data)
:_data(data)
,_next(NULL)
{}
int _data;
Node* _next;
};
void PrintListFromTailToHead(Node* pHead)
{
if(pHead == NULL)
{
return ;
}
else
{
PrintListFromTailToHead(pHead->_next);
cout<<pHead->_data<<" ";
}
}
void FunTest()
{
Node node1(1), node2(2), node3(3), node4(4);
node1._next = &node2;
node2._next = &node3;
node3._next = &node4;
PrintListFromTailToHead(&node1);
}
4.逆序销毁单链表
void DestoryFromTail(Node* pHead)
{
if(pHead)
{
DestoryFromTail(pHead->_next);
delete pHead;
pHead = NULL;
}
}
void FunTest()
{
Node* p1 = new Node(1);
Node* p2 = new Node(2);
Node* p3 = new Node(3);
Node* p4 = new Node(4);
p1->_next = p2;
p2->_next = p3;
p3->_next = p4;
DestoryFromTail(p1);
}
5.在单链表中逆序查找某个值为data的结点
Node* Select(Node* pHead,int data)
{
if(pHead)
{
Node* ret = Select(pHead->_next, data);
if(ret)
return ret;
else
{
if(pHead->_data == data)
return pHead;
}
}
return NULL;
}
void FunTest()
{
Node* p1 = new Node(1);
Node* p2 = new Node(2);
Node* p3 = new Node(3);
Node* p4 = new Node(4);
p1->_next = p2;
p2->_next = p3;
p3->_next = p4;
Node* ret = Select(p1, 3);
cout<<ret->_data <<endl;
}
6.二分查找递归形式
int BinarySearch(int *arr, int left, int right, int data)
{
if(left < right)
{
if(arr[left] == data)//先判断是否等于左右两个数
return left;
if(arr[right] == data)
return right;
int mid = (left ^ right) >> 1;
if(arr[mid] == data)
return mid;
else if(arr[mid] > data)
return BinarySearch(arr, left, mid-1, data);//[left, mid-1]
else
return BinarySearch(arr, mid+1, right, data);//[mid+1, right]
}
return -1;
}
void FunTest()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int ret = BinarySearch(arr, 0, 8, 17);
cout<<ret<<endl;
}
7.逆序打印数组中的元素
void PrintArrayFromTailToHead(int* arr, int size)
{
if(size)
{
cout<<arr[size-1]<<" ";
PrintArrayFromTailToHead(arr,size-1);
}
}
void FunTest()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
PrintArrayFromTailToHead(arr, 9);
}
8.判断一个字符串是否为回文
bool IsPalindromic(char* arr, int left, int right)
{
if(left < right)
{
IsPalindromic(arr, left+1, right-1);
if(arr[left] != arr[right])
return false;
}
return true;
}
void FunTest()
{
char* arr="1234321";
int len = strlen(arr) - 1;
int ret = IsPalindromic(arr, 0, len);
if(ret)
cout<<"true";
else
cout<<"false";
}
9.研究Perm是怎么调用的
void Perm(int* arr, int size, int N)
{
if(size == N)
{
for(size_t i = 0; i < size; i++)
cout<<arr[i]<<" ";
cout<<endl;
}
else
{
for(size_t i = N; i < size; i++)
{
std::swap(arr[i], arr[N]);
Perm(arr, size, N+1);
std::swap(arr[i], arr[N]);
}
}
}
void FunTest()
{
int arr[] = {1,2,3,4,5};
Perm(arr, 5, 3);
}
假设N = 3: