问题 H: 登记成绩

题目描述

叶老师想要用链表登记成绩。对于每张试卷有两个信息:学号和成绩。

对于登记成绩,要求学号小的成绩登记在学号大的成绩之前。

叶老师有两种操作:

1 a b:向链表中加入学号为a成绩为b的同学的成绩,题目保证不同的卷子不会有相同的学号。

2 k  : 查询当前链表中第k个同学的成绩是多少,题目保证k小于等于当前链表的长度。
请用链表做这道题!

输入

第一行输入一个整数Q,表示操作的个数。

接下来输入Q行,每一行是(1 a b)或者(2 k)格式,分别表示第一种和第二种操作。

1 <= k, Q <= 1000

1 <= a <= 1000000000
1 <= b <= 100

输出
对于每一个第二个操作,输出一个整数表示第k个同学的成绩
样例输入 
3
1 20163266 100
1 20163265 99
2 1
样例输出 Copy
99

代码如下

下面是我的ac代码,哎这个链表题对于我来说还是有点费劲,花的时间有点长了

#include<iostream>
#include<cstdlib>
#include<malloc.h>
using namespace std;
struct node
{
    int number;
    float score;
    struct node* next;
};
void insert(struct node*& head, struct node*& tail, int number, float score)
{
    struct node* Newnode = (struct node*)malloc(sizeof(struct node));
    Newnode->number = number;
    Newnode->score = score;
    Newnode->next = NULL;
    struct node* current=NULL;
    if (head == NULL || Newnode->number < head->number)
    {
        Newnode->next = head;
        head = Newnode;
    }
    else
    {
        struct node* Current = head;
        while (Current->next != NULL && Current->next->number < Newnode->number)
        {
            Current = Current->next;
        }
        Newnode->next = Current->next;
        Current->next = Newnode;
    }
    if (Newnode->next == NULL)
    {
        tail = Newnode;
    }
}
float query(struct node* head, int k)
{
    struct node* current=head;
    int count = 1;
    while (current!= NULL&&count<k)
    {
        current = current->next;
        count++;
    }
    return current->score;
}
void FreeList(struct node* head)
{
    struct node* temp=head;
    while (head != NULL)
    {
        temp = head;
        head = head->next;
        free(temp);
    }
}
int main()
{
    struct node* head = NULL;
    struct node* tail = NULL;
    int n;
    int op;
    int number;
    float score;
    int k;
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        cin >> op;
        if (op == 1)
        {
            cin >> number >> score;
            insert(head, tail, number, score);
        }
        else if (op == 2)
        {
            cin >> k;
            int a=(int)query(head, k);
            cout << a << endl;
        }
    }
    FreeList(head);
    return 0;
}

  • 21
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值