动态链表的建立和输出

题目

建立一个动态链表存放学生的学号和成绩,遇到学号是0的程序结束,并输出学生的成绩和学号

样例输入

1001,67.5

1003,87

1005,99

样例输出

Now,These 3 records are:

1001,67.5

1003,87

1005,99

代码:

#include <cstdio>
#include <iostream>
#include<algorithm>
#include<string.h>
#include<set>
#include<stdlib.h>
#include<stack>
#include<malloc.h>
#define len sizeof(struct Student)
using namespace std;
struct Student
{
  long num;
  float score;
  struct Student* next;///指向下一个元素的指针
};
int n;
struct Student*creat()///建立一个动态链表
{
  struct Student*head,*p1,*p2;
  n=0;
  p1=p2=(struct Student*)malloc(len);///开辟一个结构体大小的动态空间
  scanf("%ld,%f",&(*p1).num,&p1->score);
  head=NULL;///开始时头指针指向空
  while(p1->num!=0)
  {  
    n=n+1;
    if(n==1)
      head=p1;///头指针指向第一个输入的值
    else
      p2->next=p1;///p2一直追队尾
    p2=p1;
    p1=(struct Student*)malloc(len);///p1一直指向新建立的结点
    scanf("%ld,%f",&p1->num,&p1->score);
  }
  p2->next=NULL;///末尾的结点的指针为空
  return(head);
}
void print(struct Student*head)///输出链表的各个元素
{
  struct Student*p;
  printf("\nNow,These %d records are:\n",n);
  p=head;
  if(head!=NULL)
  do
  {  
    printf("%ld %5.1f\n",p->num,p->score);
    p=p->next;///p由当前结点指向下一个结点
  }while(p!=NULL);
}
int main()
{
  struct Student*head;
  head=creat();///只有提供头指针才能找到整个链表
  print(head);
  return 0;
}

猜你喜欢

转载自www.cnblogs.com/zhanghuawei/p/12071273.html
今日推荐