MST

星途 面试题库

面试题:C语言链表在复杂场景下的应用

假设有一个C语言程序,使用链表来管理一个任务队列,每个任务节点包含任务ID、任务优先级、任务执行函数指针等信息。节点结构定义为:struct Task { int taskID; int priority; void (*execute)(void); struct Task* next; }; 请编写一个函数,实现根据任务优先级对任务队列进行动态调整(优先级高的排在链表前面),同时保证新任务插入时不影响原有任务的执行顺序。函数原型为:void adjustTaskQueue(struct Task** head, int newTaskID, int newPriority, void (*newExecute)(void)); head为任务队列头指针的指针,newTaskID为新任务ID,newPriority为新任务优先级,newExecute为新任务的执行函数指针。
17.6万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
#include <stdio.h>
#include <stdlib.h>

struct Task {
    int taskID;
    int priority;
    void (*execute)(void);
    struct Task* next;
};

// 示例任务执行函数
void sampleExecute(void) {
    printf("执行任务\n");
}

void adjustTaskQueue(struct Task** head, int newTaskID, int newPriority, void (*newExecute)(void)) {
    struct Task* newTask = (struct Task*)malloc(sizeof(struct Task));
    newTask->taskID = newTaskID;
    newTask->priority = newPriority;
    newTask->execute = newExecute;
    newTask->next = NULL;

    if (*head == NULL) {
        *head = newTask;
        return;
    }

    struct Task* current = *head;
    struct Task* prev = NULL;

    while (current != NULL && current->priority >= newPriority) {
        prev = current;
        current = current->next;
    }

    if (prev == NULL) {
        newTask->next = *head;
        *head = newTask;
    } else {
        newTask->next = current;
        prev->next = newTask;
    }
}

可以通过以下方式调用:

int main() {
    struct Task* head = NULL;
    adjustTaskQueue(&head, 1, 3, sampleExecute);
    adjustTaskQueue(&head, 2, 2, sampleExecute);
    adjustTaskQueue(&head, 3, 3, sampleExecute);

    struct Task* current = head;
    while (current != NULL) {
        printf("任务ID: %d, 优先级: %d\n", current->taskID, current->priority);
        current = current->next;
    }

    // 释放链表内存
    current = head;
    while (current != NULL) {
        struct Task* temp = current;
        current = current->next;
        free(temp);
    }

    return 0;
}