美文网首页
【MAC 上学习 C++】Day 55-1. 实验11-2-2

【MAC 上学习 C++】Day 55-1. 实验11-2-2

作者: RaRasa | 来源:发表于2019-10-18 19:14 被阅读0次

实验11-2-2 学生成绩链表处理 (20 分)

1. 题目摘自

https://pintia.cn/problem-sets/13/problems/602

2. 题目内容

本题要求实现两个函数,一个将输入的学生成绩组织成单向链表;另一个将成绩低于某分数线的学生结点从链表中删除。

函数接口定义:

struct stud_node *createlist();
struct stud_node *deletelist( struct stud_node *head, int min_score );
函数createlist利用scanf从输入中获取学生的信息,将其组织成单向链表,并返回链表头指针。链表节点结构定义如下:

struct stud_node {
int num; /学号/
char name[20]; /姓名/
int score; /成绩/
struct stud_node next; /指向下个结点的指针*/
};
输入为若干个学生的信息(学号、姓名、成绩),当输入学号为0时结束。

函数deletelist从以head为头指针的链表中删除成绩低于min_score的学生,并返回结果链表的头指针。

输入样例:

1 zhang 78
2 wang 80
3 li 75
4 zhao 85
0
80

输出样例:

2 wang 80
4 zhao 85

3. 源码参考
#include <iostream>
#include <stdlib.h>

using namespace std;

struct stud_node {
     int    num;
     char   name[20];
     int    score;
     struct stud_node *next;
};

struct stud_node *createlist();
struct stud_node *deletelist( struct stud_node *head, int min_score );

int main()
{
    int min_score;
    struct stud_node *p, *head = NULL;

    head = createlist();
    cin >> min_score;
    head = deletelist(head, min_score);
    for ( p = head; p != NULL; p = p->next )
    {
      cout << p->num << " " << p->name << " " << p->score << endl;
    }

    return 0;
}

struct stud_node *createlist()
{
  struct stud_node *p, *head, *tail;
  int num, score;
  char name[20];

  head = tail = NULL;

  cin >> num;
  while(num != 0)
  {
    p = (struct stud_node*)malloc(sizeof(struct stud_node));

    cin >> name >> score;
    cin.ignore();

    p->num = num;
    strcpy(p->name, name);
    p->score = score;
    p->next = NULL;

    if(head == NULL)
    {
      head = p;
    }
    else
    {
      tail->next = p;
    }

    tail = p;

    cin >> num;
  }

  return head;
}

struct stud_node *deletelist( struct stud_node *head, int min_score )
{
  struct stud_node *p;
  
  p = head;
  while(p->next)
  {
    if(p->next->score < min_score)
    {
      p->next = p->next->next;
    }
    else
    {
      p = p->next;
    }
  }

  return head->next;
}

相关文章

网友评论

      本文标题:【MAC 上学习 C++】Day 55-1. 实验11-2-2

      本文链接:https://www.haomeiwen.com/subject/dhbhmctx.html