1. 输出一个字符串中字符的两两组合。如字符串"ABAC",则输出AB、AA、AC、BA、BC、AC
#include <stdio.h>
#include <string.h>
void two_ele_subs(const char *s)
{
const char *p=s+1;
if(strlen(s) == 1 || strlen(s) == 0)
return;
if(strlen(s) == 2)
{
printf("%s", s);
return;
}
else if(*(s+2))
for(; *p; p++)
printf("%c%c \n", *s, *p);
two_ele_subs(++s);
}
int main()
{
const char *s="ABAC";
two_ele_subs(s);
printf("\n");
return 0;
}
#include <string.h>
void two_ele_subs(const char *s)
{
const char *p=s+1;
if(strlen(s) == 1 || strlen(s) == 0)
return;
if(strlen(s) == 2)
{
printf("%s", s);
return;
}
else if(*(s+2))
for(; *p; p++)
printf("%c%c \n", *s, *p);
two_ele_subs(++s);
}
int main()
{
const char *s="ABAC";
two_ele_subs(s);
printf("\n");
return 0;
}
2. 递归实现 f(x, y)=x-y if x<0或y<0
f(x, y)=f(x-1, y) + f(x, y-1) 其他
int recursion_fxy(int x, int y)
{
if(x<0 || y<0)
return x-y;
else
return recursion_fxy(x-1, y) + recursion_fxy(x, y-1);
}
{
if(x<0 || y<0)
return x-y;
else
return recursion_fxy(x-1, y) + recursion_fxy(x, y-1);
}
3. 递归输出单链表
void print_list(LNode *head)
{
if(head==NULL)
printf("\n");
else
{
printf("%c->", head->data);
print_list(head->next); /* 递归输出单链表中的元素 */
}
}
{
if(head==NULL)
printf("\n");
else
{
printf("%c->", head->data);
print_list(head->next); /* 递归输出单链表中的元素 */
}
}
4. 递归查找某个元素是否存在单链表中
#include <stdio.h>
#include <stdlib.h>
#define MALLOC(type) (type *)malloc(sizeof(type))
typedef char ElemType;
typedef struct LNode {
ElemType data;
struct LNode *next;
} LNode;
LNode *create_list() /* 创建单链表 */
{
LNode *p, *prep, *newp;
p=MALLOC(LNode);
scanf("%c", &p->data);
prep=p;
for(int i=0; i<9; i++)
{
newp=MALLOC(LNode);
scanf("%c", &newp->data);
prep->next=newp;
prep=newp;
}
prep->next=NULL;
return p;
}
int exit_node(LNode *head, char target) /* 递归查找单链表中是否有target元素 */
{
LNode *curp=head;
if(curp != NULL)
{
if(target == curp->data)
return 1;
else
return exit_node(curp->next, target); /* 递归查找 */
}
return 0;
}
int main()
{
char ch='A';
LNode *head=NULL;
head=create_list();
printf("Letter %c %s \n", ch, exit_node(head, ch) ? "exists!": "does not exist!");
return 0;
}
#include <stdlib.h>
#define MALLOC(type) (type *)malloc(sizeof(type))
typedef char ElemType;
typedef struct LNode {
ElemType data;
struct LNode *next;
} LNode;
LNode *create_list() /* 创建单链表 */
{
LNode *p, *prep, *newp;
p=MALLOC(LNode);
scanf("%c", &p->data);
prep=p;
for(int i=0; i<9; i++)
{
newp=MALLOC(LNode);
scanf("%c", &newp->data);
prep->next=newp;
prep=newp;
}
prep->next=NULL;
return p;
}
int exit_node(LNode *head, char target) /* 递归查找单链表中是否有target元素 */
{
LNode *curp=head;
if(curp != NULL)
{
if(target == curp->data)
return 1;
else
return exit_node(curp->next, target); /* 递归查找 */
}
return 0;
}
int main()
{
char ch='A';
LNode *head=NULL;
head=create_list();
printf("Letter %c %s \n", ch, exit_node(head, ch) ? "exists!": "does not exist!");
return 0;
}

浙公网安备 33010602011771号