结构体9

作者: 时间:2020-07-09 点击数:

//输出链表内容函数
void printlist(struct node *head)
{
struct node *p;
p=head;
if (p!=NULL)
{
 p=p->next;
 while (p->next!=NULL)
 {
  printf("%s,%d->",p->name,p->score);
  p=p->next;
 }
 //单独处理一下最后一个节点
 printf("%s,%d",p->name,p->score);
}
}
struct node *count(struct node *p)  //接收头指针的值  
  {
      struct node *t=NULL;
   if (p!=NULL)
   {
      p=p->next; //p指向第一个数据节点
   t=p;  //t指向第一个数据节点,接着把剩余的节点的成绩值跟t指向节点的成绩比较
   if (p!=NULL) p=p->next;  //p指向t后边的那个节点
   while (p!=NULL)
   {
       if (p->score>t->score) t=p;
    p=p->next;
   }
   }      
   return t;
  }
//递归函数求最大值
struct node *f(struct node *p)
{
    struct node *m;
 if (p->next==NULL)
 m=p;
 else
 {
    m=f(p->next);
    if (m->score<p->score)
    m=p;
 }
 return m;
}
int main()
{
struct node *head=NULL;  //头指针
struct node *p;
int n;
scanf("%d",&n);
createlist(head,n);    //head 类型 struct node * ,  &head  类型    struct node **
printlist(head);
p=count(head);
printf("\n%s,%d\n",p->name,p->score);
p=f(head->next);
printf("\n%s,%d\n",p->name,p->score);
return 0;
}

/*
链表的应用:
问题:一个班5个学生,学生信息(姓名,成绩),利用链表求该班成绩最好的学生。
     struct node
  {
      char name[20];
   int score;
   struct node *next;
  };
  设计统计函数:
  struct node *count(struct node *p)  //接收头指针的值  
  {
      struct node *t=NULL;
   if (p!=NULL)
   {
      p=p->next; //p指向第一个数据节点
   t=p;  //t指向第一个数据节点,接着把剩余的节点的成绩值跟t指向节点的成绩比较
   if (p!=NULL) p=p->next;  //p指向t后边的那个节点
   while (p!=NULL)
   {
       if (p->score>t->score) t=p;
    p=p->next;
   }
   }      
   return t;
  }
递归:利用链表求该班成绩最好的学生
     (1)定义是递归    (2)存储结构是递归   (3)算法是递归的
   递归函数设计:
(1)建立模型  f(p) 返回成绩最好的学生  struct node *   p:指向第一个数据节点
(2)最简单情况   当数据节点只有一个  意味着p->next=NULL    函数的返回值:p节点
(3)假设f(p->next) 已经求出来    f(p)=max(f(p->next),p)  
struct node *f(struct node *p)
{
    struct node *m;
 if (p->next==NULL)
 m=p;
 else
 {
    m=f(p->next);
    if (m->score<p->score)
    m=p;
 }
 return m;
}
统计链表节点个数?   平均值?
*/
/*
C++引用:
int m;
int &n=m;  //相等于给变量m起了个别名n,
//n、m的操作是完全一样的。

*/
/*
#include <stdio.h>
void fun(int &y)
{
y=y+50;  //x=x+50
}
int main()
{
int x;
x=20;
printf("%d\n",x);
fun(x);
printf("%d\n",x);
return 0;
}

上一页 [1] [2]

Copyright© 2020 Anyang Institute of Technology.All rights reserved.

学院地址:河南省安阳市黄河大道西段