#include
#include
#define N 4
struct node{
int score;
struct node*link;
};
struct node node;
struct node*list,*p,*r,*q;
void input(struct node*list)
{
int i;
int ch;
for(i=0;i
{
printf("please input the score of %d\t",i+1);
p=(struct node*)malloc(sizeof(struct node*));
scanf("%d",&p->score);
p->link=NULL;
if(list==NULL)
list=p;
else
r->link=p;
r=p;
printf("數據為%d",p->score);
}
}
void average(struct node*list)
{
int s=0,i;
double average2;
if(list==NULL)
printf("鏈表為空");
for(i=0;i
{
s+=list->score;
list=list->link;
}
average2=(double)s/N;
printf("%f",average2);
}
void print(struct node*list)
{
int i;
printf("順利進入");
if(list==NULL)
printf("這是空鏈表");
else
{
q=list;
while(q->link!=NULL)
{
printf("%d",q->score);
q=q->link;
}
}}
int main()
{
void input(struct node*list);
void average(struct node*list);
void print(struct node*list);
int ah;
system("cls");
while(1){
printf("鏈表操作系統:");
printf("\n1.建立鏈表\n2.輸出數據\n3.求平均數\n");
scanf("%d",&ah);
switch(ah){
case 1:input(list);break;
case 2:print(list);break;
case 3:average(list);break;
default:printf("wrong!");break;
}}}
樓主直接復制跑一下
#include<iostream>
#include<stdio.h>
using namespace std;
#define N 4
struct node{
int score;
struct node*link;
};
struct node node;
struct node*list,*p,*r,*q;
void input()
{
int i;
int ch;
list = NULL;
for(i=0;i < N; i++)
{
p=(struct node*)malloc(sizeof(struct node));
printf("please input the score of %d\t",i+1);
scanf("%d",&p->score);
p->link=NULL;
if(list==NULL)
list=p;
else
r->link=p;
r=p;
printf("數據為%d",p->score);
}
}
void average()
{
int s=0,i;
double average2;
if(list==NULL)
printf("鏈表為空");
for(i=0;i < N; i++)
{
s+=list->score;
list=list->link;
}
average2=(double)s/N;
printf("平均值為:%lf\n",average2);
}
void print()
{
int i;
printf("順利進入\n");
if(list==NULL)
printf("這是空鏈表");
else
{
q=list;
while(q!=NULL)//這裡只需要判斷q就行
{
printf("%d\n",q->score);
q=q->link;
}
}}
int main()
{
void input();
void average();
void print();
int ah;
system("cls");
while(1){
printf("鏈表操作系統:");
printf("\n1.建立鏈表\n2.輸出數據\n3.求平均數\n");
scanf("%d",&ah);
switch(ah){
case 1:input();break;
case 2:print();break;
case 3:average();break;
default:printf("wrong!");break;
}
}
}
有幾個問題:
1.既然list指針已經變成全局的了,就不要傳參了,樓主那樣傳一級指針是沒有用的,操作的都是list的一個副本,所以就算插入的代碼沒錯,
也會輸出是空鏈表(傳二級指針可以解決)
2.輸出的函數裡while循環只要判斷while(q!=NULL)就行了
運行結果: