c - 如何按日期对链接列表进行排序?

标签 c data-structures linked-list sorting

我们假设使用排序链接列表创建一个带有标题、一些详细信息、日期和分类优先级的调度程序。

我设法按优先级对它们进行排序,但首先我必须按日期对它们进行排序。 由于我使用的日期是一个具有 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;
        }
}

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

最佳答案

// 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);
}

关于c - 如何按日期对链接列表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33688931/

相关文章:

c - 在链表中,最后一个节点->下一个不为NULL,导致段错误

c - 如何从二进制输入文件创建链表?前几个字节是 int,接下来的几个字节是 char,依此类推

c - dup2() 和 exec()

c++ - 具有嵌套结构的动态数组

algorithm - 不定长数组

c++ - 有没有rand()以外的随机生成库,开发者可以手动设置seed?

algorithm - 给出 n 节点二叉搜索树高度的渐近上界,其中节点的平均深度为 Θ(lg n)

c - C错误中的LinkedList

c++ - 后缀表示法计算器 (RPN) 问题 C++

c - Yacc 如何扩展这条规则呢?