編程練習(用遞歸處理線性表的問題)
阿新 • • 發佈:2019-03-29
name average ios sum stream -o 申請 std 當前 include
include
cin >> num;//輸入數據
if (num == 0)
{
L = NULL;
return OK;
} //結束
else
{
L = new LNode; //申請新的節點,指針指向結構體
L->data = num; //先將數據放到數據域
return Creat_LinkList(L->next); //遞歸創建節點
}
}
}
else{
double ave = (sum + L->data)/(i+1);
return ave;
}
if (L->next == NULL)
cout << "\n當前鏈表為空" << endl << endl;
else{
cout << "\n此時表中結點個數是";
cout << count(L);
cout << "\n此時表中元素總和的平均值是";
cout << getAverage_List(L,0,0) << endl << endl;
}
}
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退出):";
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;
cout << "\n當前鏈表為空" << endl << endl;
else{
cout << "\n此時表中結點個數是";
cout << count(L);
cout << "\n此時表中元素總和的平均值是";
cout << getAverage_List(L,0,0) << endl << endl;
}
}
編程練習(用遞歸處理線性表的問題)