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

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

作者: RaRasa | 来源:发表于2019-10-17 20:35 被阅读0次

实验11-2-1 建立学生信息链表 (20 分)

1. 题目摘自

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

2. 题目内容

本题要求实现一个将输入的学生成绩组织成单向链表的简单函数。

函数接口定义:

void input();
该函数利用scanf从输入中获取学生的信息,并将其组织成单向链表。链表节点结构定义如下:

struct stud_node {
int num; /学号/
char name[20]; /姓名/
int score; /成绩/
struct stud_node next; /指向下个结点的指针*/
};
单向链表的头尾指针保存在全局变量head和tail中。

输入为若干个学生的信息(学号、姓名、成绩),当输入学号为0时结束。

输入样例:

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

输出样例:

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

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

using namespace std;

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

void input();

int main()
{
    struct stud_node *p;
    
    head = tail = NULL;
    input();

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

    return 0;
}

void input()
{
  struct stud_node *p;
  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;
}

相关文章

网友评论

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

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