【问题标题】:How to sort linked list by date?如何按日期对链表进行排序?
【发布时间】:2015-11-13 08:55:59
【问题描述】:

我们假设使用排序链表制作一个带有标题、一些细节、日期和分类优先级的调度程序。

我设法按优先级对它们进行了排序,但首先我必须按日期对它们进行排序。 由于我使用的日期是一个 int 月、int 日、int 年的结构。我无法同时对所有 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;
        }
}

我可以得到任何提示和帮助吗?

【问题讨论】:

  • 好吧,您可以将这三段数据合并为一个整数,例如10000*y + 100*m + d。或者你可以写一个比较函数,分别比较两个日期的年月日。
  • @Oehm,喘不过气来!删除了评论。

标签: c data-structures linked-list sorted


【解决方案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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-15
    • 1970-01-01
    • 2018-03-30
    • 2016-10-15
    • 2021-03-26
    • 1970-01-01
    相关资源
    最近更新 更多