您的位置:首页 > 编程语言 > C语言/C++

厦大C语言上机 1402 第K早之日

2018-01-13 13:19 796 查看
1402.第K早之日

时间限制: 1000 MS          内存限制: 65536 K

        

提交数: 396 (0 users)          通过数: 223 (214 users)

问题描述

写一个结构体变量(包括年月日),输入N个年/月/日信息,用链表保证其有序,在输入一个k,最后输出第k天,即给定输入的时间最早的第k天。

输入格式

第一行输入一个整数N,表示给定的天数。

接下来N行,每行给出形如YYYY/MM/DD的格式,代表YYYY年MM月DD日。(例如:1991/06/21,0123/02/01)

最后一行一个整数K(1<=K<=N),如题所述。

输出格式

仅一行,输出给定的日子里面第K早之日,输出格式与输入格式相同。

样例输入

4

1937/05/23

1991/02/15

1946/10/30

1999/06/09

2

样例输出

1946/10/30

来源
xmu

#include <stdio.h>
#include <stdlib.h>

struct Date
{
int year;
int month;
int day;
struct Date *next;
};

void insert(struct Date *list, int year, int month, int day)
{
struct Date *p, *q, *r;

r = (struct Date*)malloc(sizeof(struct Date));
r->year = year;
r->month = month;
r->day = day;
r->next = NULL;

q = list;
p = list->next;
while (p)
{
if ((p->year < year) ||
(p->year == year && p->month < month) ||
(p->year == year && p->month == month && p->day < day))
{
q = p;
p = p->next;
}
else
{
q->next = r;
r->next = p;
return;
}
}
q->next = r;
r->next = p;
}

void retrieve(struct Date *list, int k)
{
struct Date *p = list->next;
int count = 0;

while (p)
{
count++;
if (count == k)
{
printf("%04d/%02d/%02d\n", p->year, p->month, p->day);
return;
}
p = p->next;
}
}

int main()
{
int n;
int year, month, day;
int k;
struct Date *list;

list = (struct Date *)malloc(sizeof(struct Date));
list->next = NULL;

scanf("%d", &n);
while (n--)
{
scanf("%d/%d/%d", &year, &month, &day);
insert(list, year, month, day);
}
scanf("%d", &k);
retrieve(list, k);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: