0
点赞
收藏
分享

微信扫一扫

我这个链表程序咋回事呀,怎么输不进去数据呀?

松鼠树屋 2022-03-12 阅读 143
链表

#include<stdio.h>

#include<stdlib.h>

 

typedef struct link{

 int date;

 struct link *next;

}link,*linklist;

 

void print(linklist head)

{

 linklist p=head;

 while(p !=NULL){

  

  printf("%d ",p->date );

  p=p->next ;//让P指向下一个节点 

  

 }

 printf("\n");

}

 

linklist delete_list(linklist head,int x)

{

 linklist p=head->next ,pr=head;

 while(p->next !=NULL){//未到表尾 

  if(p->date ==x){

   if(p==head){//若待删除节点是头结点 

    head=p->next ;

   }else{

       pr->next =p->next ;//让前一节点的指针域指向后一节点的指针域 

   }

     free(p);//必须释放待删节点所占用的内存,以防内存泄漏 

  }else{

      pr=p;

   p=p->next ;

    

  }

 }

 print(head);

 return head;

}

linklist insert_list(linklist head,int date)

{

 linklist p=head,pr=NULL;//pr是新结点的指针

  

 int x;

 

 pr=(linklist)malloc(sizeof(link));

 

 if(pr==NULL){

  printf("No enough memory to allocate!\n");

  exit(0);

 }else{

  while(p->next !=NULL){

   p=p->next ;

  }

  p->next =pr;//让末节点的指针指向新节点 

 }

 //输入新的节点的数据 

 pr->date =date;

 pr->next =NULL;

 print(head);

 

 scanf("%d",&x);//待在链表中删除的数据 

 head=delete_list(head,x);

 

 return head;

}

linklist CreatList_NULL(linklist head)

{

 link *p=NULL;

 p=(linklist)malloc(sizeof(link));

 if(p==NULL){

  printf("No enough memory to allocate!\n");

  exit(0);

 }else{

  p->next =NULL;

 }

 return head;

}

linklist CreatList(linklist head)

{

 int x,a;

    linklist p=NULL,pr=head;

    

    scanf("%d",&x);//每个节点的值 

    

    while(x!=-1){

     p=(linklist)malloc(sizeof(link));//建立新节点 

     if(p==NULL){

   printf("No enough memory to allocate!\n");

   exit(0);

  }else{

      pr->next=p;

   p->date =x;

   pr=p;

   scanf("%d",&x);

     }

 }

 p->next =NULL;

 //创建好了单链表 

 print(head);

 

 scanf("%d",&a);//待在链表中插入的数据 

 head=insert_list(head,a);//调用插入函数 

 

 return head;

}

void Aver(linklist head)

{

 linklist p=head;

 int sum=0,count=0;

 double aver=0.0;

 while(p!=NULL){

  sum+=p->date ;

  p=p->next ;

  count++;

 }

 aver=1.0*sum/count;

 printf("%f",aver);

}

int main()

{

 link *head=NULL; 

 

 head=CreatList_NULL(head);

 head=CreatList(head); 

 Aver(head);

   

  return 0;

举报

相关推荐

0 条评论