编程练习(用递归处理线性表的问题)

include

include

using namespace std;

define OK 1

define ERROR 0

typedef int Status;

typedef struct LNode
{
int data;//结点的数据域
struct LNode next;//结点的指针域
}LNode,
LinkList;//LinkList为指向结构体LNode的指针类型

Status Creat_LinkList(LinkList &L)//创建链表,当输入数字为0时,令当前指针为空
{
int num;
cout << "请每行输入一个数据元素并按回车(直到0退出):";
cin >> num;//输入数据
if (num == 0)
{
L = NULL;
return OK;
} //结束
else
{
L = new LNode; //申请新的节点,指针指向结构体
L->data = num; //先将数据放到数据域
return Creat_LinkList(L->next); //递归创建节点
}
}

double getAverage_List(LinkList L, double sum, int i)
{
if (L->next != NULL){
sum = sum + L->data;
return getAverage_List(L->next, sum, i+1);
}
else{
double ave = (sum + L->data)/(i+1);
return ave;
}

}

int count(LNode *L)
{
if(L==NULL)
{
return 0;
}
else
{
return count(L->next)+1;
}
}

int main(){
LinkList L;
if (Creat_LinkList(L))
cout << "\n成功创建单链表" << endl;
else
cout << "\n创建单链表失败" << endl;
if (L->next == NULL)
cout << "\n当前链表为空" << endl << endl;
else{
cout << "\n此时表中结点个数是";
cout << count(L);
cout << "\n此时表中元素总和的平均值是";
cout << getAverage_List(L,0,0) << endl << endl;
}
}

转载于:https://www.cnblogs.com/ggad/p/10618580.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值