#include<stdio.h>#include<stdlib.h>#include<malloc.h>#defineERROR0#defineOK1typedefint ElemType;typedefint Status;// definition of node structure of singly linked listtypedefstructL_node{
ElemType data;// data field structL_node*next;// pointer field} LNode,*LinkedList;// Initialize a singly linked list L with head node
Status InitList_L(LinkedList *L){// Allocate memory for head node(*L)=(LinkedList)malloc(sizeof(LNode));if(!(*L))return ERROR;(*L)->next =NULL;return OK;}// 输入若干整数(以输入-1作为结束条件,-1不包含在单链表中),用递归方法创建一个不带头结点的单链表。
Status CreateList_L(LinkedList L){
ElemType input;scanf("%d",&input);if(input ==-1){// Set the next pointer of the last node to NULL
L->next =NULL;return OK;}// Allocate memory for the next node
L->next =(LinkedList)malloc(sizeof(LNode));if(!L->next)return ERROR;// Assign input value to the data field of the next node
L->next->data = input;// Recursively create the next nodeCreateList_L(L->next);return OK;}// Print the elements in a listvoidLinkedListPrint(LinkedList L){// Base case: If the next node is NULL, returnif(!L->next)return;// Print the data of the next nodeprintf("%d ", L->next->data);// Recursively print the rest of the listLinkedListPrint(L->next);}intmain(){
LinkedList La;// Initialize the linked listInitList_L(&La);// Create the linked list using recursionCreateList_L(La);// Print the linked listLinkedListPrint(La);return0;}
3. 递归实验–汉诺塔
#include<stdio.h>#include<stdlib.h>#include<string.h>staticint step =0;//移动函数voidmove(int n,char*A,char*B){printf("将%d从%c移动到%c.\n", n,*A,*B);
step++;return;}//将n层汉诺塔从A移动到C,B作为辅助voidHanoi(int n,char*A,char*B,char*C){if(n ==1)move(n, A, C);// 只有一层时直接从 A 移动到 Celse{Hanoi(n -1, A, C, B);// 将 n-1 层汉诺塔从 A 移动到 B,以 C 为辅助move(n, A, C);// 将第 n 层从 A 移动到 CHanoi(n -1, B, A, C);// 将 n-1 层汉诺塔从 B 移动到 C,以 A 为辅助}}intmain(){int n;char axle[3]={'A','B','C'};printf("输入层数n:");scanf("%d",&n);Hanoi(n, axle, axle +1, axle +2);printf("移完%d层汉诺塔所用总步数为%d\n", n, step);return0;}