我们假设使用已排序的链接列表制作一个带有标题,一些细节,日期和分类优先级的调度程序。
我设法按优先顺序对它们进行排序,但首先我必须按日期对它们进行排序。 由于我使用的日期是一个int月,int day,int year的结构。我无法同时对所有3个进行排序。我只能弄清楚如何每年或每天或每月排序。
这是我用于排序日期的虚拟代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct D{
int month;
int day;
int year;
}DATE;
typedef struct node_tag{
DATE d;
struct node_tag * next;
}NODE;
int main(){
NODE *head = NULL;
NODE *temp, *ptr, *print;
int usr = 1;
while(usr!=0){
DATE date;
scanf("%d", &usr);
printf("Enter date: ");
scanf("%d %d %d", &date.month, &date.day, &date.year);
temp = (NODE *)malloc(sizeof(NODE));
temp->d.month = date.month;
temp->d.day = date.day;
temp->d.year = date.year;
temp->next = NULL;
if(head == NULL || head->d.year > temp->d.year){
temp->next = head;
head = temp;
}
else if(head == NULL || head->d.year == temp->d.year){
if(head->d.month > temp->d.month){
temp->next = head;
head = temp;
}
}
else{
ptr = head;
while(ptr->next !=NULL && ptr->next->d.year < temp->d.year){
ptr = ptr->next;
}
temp->next = ptr->next;
ptr->next = temp;
}
}
print = head;
while(print!= NULL){ //prints the list
printf("%d %d %d\n", print->d.month, print->d.day, print->d.year);
print = print->next;
}
}
我可以获得任何提示和帮助吗?
答案 0 :(得分:1)
// On the lines of M oehm's 2nd approach
// Given the way you store the time, this should work
int date_compare(DATE *t1, DATE *t2) {
// returns 1 if t1 greater than t2, -1 if t1 < t2, 0 if equal
if (t1->year > t2->year) return(1);
if (t1->year < t2->year) return(-1);
// year matches. so check month
if (t1->month > t2->month) return(1);
if (t1->month < t2->month) return(-1);
// month aslo matches. so check day
if (t1->day > t2->day) return(1);
if (t1->day < t2->day) return(-1);
// day also matches
return(0);
}