题目描述
叶老师想要用链表登记成绩。对于每张试卷有两个信息:学号和成绩。
对于登记成绩,要求学号小的成绩登记在学号大的成绩之前。
叶老师有两种操作:
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
输出
样例输入
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;
}