3.12写出下面程序的调用结果:
(1) void P1(int W);
{ int A,B;
A=W-1; B=W+1;
cout<<A<<B;
}
void P2(W int );
{ int A,B;
A=2*W; B=W*W;
P1(A); P1(B);
cout<<A<<B;
}
调用 P2(5);
输出:9 11 24 26
(2) int Hcf(int M,int N)
{ int H;
while (N!=0)
{
H=M % N;
M=N; N=H
} ;
cout<<M; return M;
} ;
调用 cout<<Hcf(100, 350);
cout<<Hcf(200, 49);
输出:50 1
1 49
(3) int Hcf(int M, int N)
{ int H;
while (N!=0)
{
H=M mod N;
M=N; N=H
}
return M;
}
void reduce(int M1, int N1; int *M2, int *N2)
{ int R;
R=Hcf(M1,N1);
*M2=M1 / R; *N2=N1/ R;
cout<<M1<<'/'<<N1<<'='<<M2<<'/'<<N2;
}
调用 reduce(100,200, X,Y);
reduce(300,550, M,N);
输出:100/200=1/2
300/550=6/11
3.13阅读下列程序,并写出其运行结果:
(2) void P(int W)
{
if (W>0)
{ cout<<W;
P(W-1);
}
}
调用 P(4);输出:4 3 2 1
(4) void P(int W)
{
if (W>0)
{ P(W-1);
P(W-1);
cout<<W;
}
}
调用 P(4);
输出:1 1 2 1 1 3 1 1 2 1 1 4
(6) void P(int N,int *F);
{
if (N==0)
*F=0;
else { P(N-1, *F); F=F+N; }
}
调用 P(4,*M); cout<<*M
输出:10
3.14求解下面各调用的结果, 并指出算法的功能。
(1) void PrintRV(int N)
{
if (N>0)
{ cout<<N % 10;
PrintRV(N / 10);
}
} ;
调用PrintRV(12345);
输出:54321
(2) void PC(int M, int N; int *K );
{
if (N==0)
*K=1;
else { PC(M-1,N-1,*K); *K=*K*M / N; }
} ;
调用 PC(10,4,*M); cout<<*M;
210
(3) int SS(int N)
{
if (N==0 ) return 100;
else return SS(N-1)+N*N;
}
调用 cout<<SS(5);
115
(4) int ACM(int M, int N)
{
if (M==0) return N+1;
else if (N==0) return ACM(M-1,1);
else return ACM(M-1,ACM(M,N-1));
}
调用 cout<<ACM(2,2);
7
4.不带头结点的单链表,试写出递归算法求链表的长度。
#include <iostream>
// 定义链表节点结构
struct ListNode {
int val;
ListNode* next;
};
// 递归函数,用于计算链表的长度
int getLinkedListLength(ListNode* head) {
// 递归终止条件:当链表为空时,长度为0
if (head == nullptr) {
return 0;
}
// 递归调用:计算链表头节点之后的子链表的长度,并加上1(当前节点)
return 1 + getLinkedListLength(head->next);
}
int main() {
// 创建链表
ListNode* node1 = new ListNode{1, nullptr};
ListNode* node2 = new ListNode{2, nullptr};
ListNode* node3 = new ListNode{3, nullptr};
ListNode* node4 = new ListNode{4, nullptr};
node1->next = node2;
node2->next = node3;
node3->next = node4;
// 计算链表长度
int length = getLinkedListLength(node1);
// 输出结果
std::cout << "链表的长度为:" << length << std::endl;
// 释放链表内存
delete node1;
delete node2;
delete node3;
delete node4;
return 0;
}