这是使用双指针实现简单优先级队列的正确方法吗?

时间:2018-01-05 01:18:23

标签: c

我试图应用linus torvald的“好品味”的想法,当他展示了一个使用双指针消除if语句来删除单个链接列表的条目的例子。我想知道在应用相同想法的优先级队列中排队和出列的最佳方法。

    #include <stdlib.h>
    #include <stdio.h>

    typedef struct node node;
    struct node{
        int val;
        node *prev;
    };

    node *head = NULL;

    void enqueue(int val){
        node **focus = &head;
        while((*focus) != NULL && (*focus)->val <= val)
            focus = & (*focus)->prev;
        node *tmp = *focus;                      //is there a way to remove this line
        *focus  = (node*)malloc(sizeof(node));
        **focus = (node){ .val = val, .prev = tmp };
    }

    int dequeue(){
        int ret = head->val;
        node *tmp = head;  
        head = head->prev;
        free(tmp);
        return ret;
    }

    int main(){
        enqueue(20);
        enqueue(11);
        enqueue(4);
        enqueue(6);
        enqueue(9);
        enqueue(8);
        enqueue(27);
        enqueue(44);
        printf("dequeue: %d\n",dequeue());
        printf("dequeue: %d\n",dequeue());
        printf("dequeue: %d\n",dequeue());
        printf("dequeue: %d\n",dequeue());
        printf("dequeue: %d\n",dequeue());
        printf("dequeue: %d\n",dequeue());
        printf("dequeue: %d\n",dequeue());
    }

0 个答案:

没有答案