题目1:
请用递归算法计算n的阶乘
特殊情况当n小于0时,阶乘是没有意义的。
当n=0时,阶乘为1。
#include <iostream>
using namespace std;
long long jiechengcore(long a)
{
if(a==1)
return 1;
else
return a*jiechengcore(a-1);
}
long long jiecheng(long a)
{
if(a<0)
return 0;
else if(a==0)
return 1;
else
return jiechengcore(a);
}
int main()
{
cout<<jiecheng(-1)<<endl;
cout<<jiecheng(0)<<endl;
cout<<jiecheng(5)<<endl;
cout<<jiecheng(14)<<endl;
}
2、已知一个链表的结点结构,并已知链表的头结点head,写一个函数把这个链表逆序(比如一个链表1->2->3->4->5通过反转后成为5->4->3->2->1,即为链表逆序)。链表的结点结构为:
struct Node{int data;Node *next;};
typedef struct Node Node;
struct Node
{
int data;
Node * next;
};
typedef struct Node Node;
void print(Node *head)
{
while(head!=NULL)
{
cout<<head->data<<" ";
head=head->next;
}
cout<<endl;
}
Node * createlist(int *arr,int len)
{
if(arr==NULL||len<=0)
return NULL;
Node *head=new Node;
Node *p=head;
for(int ii=0;ii<len;ii++)
{
Node * temp=new Node;
temp->data=arr[ii];
temp->next=NULL;
p->next=temp;
p=temp;
}
p=head;
head=head->next;
delete p;
return head;
}
void reverse(Node **head)
{
if(head==NULL||*head==NULL)
return;
Node *p1=*head;
Node *p2=p1->next;
while(p2!=NULL)
{
Node *p3=p2->next;
p2->next=p1;
p1=p2;
p2=p3;
}
(*head)->next=NULL;
*head=p1;
}
int main()
{
int arr[10]={};
for(int ii=0;ii<10;ii++)
arr[ii]=ii;
Node *head=createlist(arr,10);
print(head);
reverse(&head);
print(head);
return 0;
}
测试结果: