c - 如何更改此队列顺序?

标签 c data-structures queue

现在,在我的代码队列中顺序是

normal node -> normal node -> item node -> null

前面指出普通节点,但我要指出项目节点!

所以,我想更改代码顺序

item node -> normal node -> normal node -> null

我的代码是,,

    void LQ_CreateQueue(LinkedQueue **Queue)
{
    (*Queue) = (LinkedQueue*)malloc(sizeof(LinkedQueue));
    (*Queue)->Front = NULL;
    (*Queue)->Rear = NULL;
    (*Queue)->count = 0;
}

Node *LQ_CreateNode(int NewData)
{
    Node *NewNode = (Node*)malloc(sizeof(Node));

    if (NewData == 7) 
        NewNode->Priority = ItemBlock;
    else 
        NewNode->Priority = NormalBlock;

    NewNode->rand_value = NewData;
    NewNode->NextNode = NULL;

    return NewNode;
}

void LQ_DestroyNode(Node *_Node)
{
    free(_Node);
}

void LQ_Enqueue(LinkedQueue *Queue, Node *NewNode)
{
    if (Queue->Front == NULL)
    {
        Queue->Front = NewNode;
        Queue->Rear = NewNode;
        Queue->count++;
    }
    else
    {
        Queue->Rear->NextNode = NewNode;
        Queue->Rear = NewNode;
        Queue->count++;
    }
}

Node *LQ_Dequeue(LinkedQueue *Queue)
{
    Node *Front = Queue->Front;

    if (Queue->Front->NextNode == NULL)
    {
        Queue->Front = NULL;
        Queue->Rear = NULL;
    }
    else
    {
        Queue->Front = Queue->Front->NextNode;
    }

    Queue->count--;

    return Front;
}

int LQ_IsEmpty(LinkedQueue *Queue)
{
    return (Queue->Front == NULL);
}

帮帮我。

这段代码由CreateQueue、CreateNode、DeleteNode、InsertNode、PrintNode、CheckEmptyQueue函数组成。按顺序..

如何更改该代码?

最佳答案

实际上,在阅读了更多有关您的代码的信息后,您似乎想要的是一种队列,称为优先级队列。保持它们有序的“ secret ”是,当插入新节点时,您从头到尾遍历列表以找到插入节点的位置。

就您而言,由于您只有两个优先级,因此更简单:

  • 如果插入“普通节点”,则找到最后一个“项目节点”,并将“普通节点”插入到最后一个“项目节点”之后(创建新的“普通节点”NextNode 指针等于最后一个“项目节点”NextNode 指针(通过简单的赋值),然后使最后一个“项目节点”NextNode 指针指向新的“普通节点” ”,请注意操作顺序很重要)

  • 如果插入“项目节点”,则只需将其添加到队列的开头即可。

或者上述的一些变体。

关于c - 如何更改此队列顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46794084/

相关文章:

c - C中 float 的平方

python - SWIG C/python 和无符号字符指针

C++ 二叉搜索树 - 复杂类型

algorithm - 绳索的高效重新散列

algorithm - 为什么我们要从队列中删除s?

linux - 等待队列中的唤醒进程

c - 我如何在 C 中打印一个字符串,使其显示像\n、\o 等字符?

c - mbrtowc 的 s==NULL 案例的目的是什么?

algorithm - 图数据结构的最坏情况内存

Java 队列和堆栈