循环链表中的队列

时间:2015-11-15 13:36:43

标签: c linked-list queue

你好我在C中进行广度优先遍历,因此我需要实现一个队列,我想用双指针和循环链表实现它。我知道它一定不是最简单的,但我想了解更多!

这是我的结构:

struct queue
{
    void         *val;
    struct queue *next;
};

这是我的推送:

void queue_push(struct queue **q, void *p) {
    struct queue *tmp = malloc(sizeof(struct queue));
    tmp->val = p;
    if(q)
    {
            tmp->next = (*q)->next;
            (*q)->next = tmp;
    }
    else
    {
            tmp->next = tmp;
    }
}

如果我在每行打印printf它告诉我"非法指令(核心转储)" at"(* q) - > next = tmp;"而且我不知道自己出了什么问题。

编辑:我必须保持此结构不变

void tree_breadth_print(struct tree *t)
{
    struct queue **q = malloc(sizeof(struct queue));
    struct tree *tmp = malloc(sizeof(struct queue));

    if(t == NULL)
    {
            printf("Tree is empty\n");
            return;
    }
    queue_push(q, t);

    while(!queue_is_empty(*q))
    {
            tmp = queue_pop(q);
            printf("%d", tmp->key);

            if(tmp->left != NULL)
                    queue_push(q, tmp->left);
                    printf("tmp->left->key = %d \n", tmp->left->key);
            if(tmp->right != NULL)
                    queue_push(q, tmp->right);
    }
    free(q);
    printf("\n");
}

Tree结构很简单:

struct tree {
    int           key;
    struct tree  *left, *right;
};

2 个答案:

答案 0 :(得分:0)

您可以为您的程序遵循此结构。 我会稍微更改您使用的名称: 考虑以下结构:

struct Node{
    int val;//supposing the type is int
    struct Node *next;
    struct Node *prev;
};typedef struct Node Node;
//
//
//
typedef struct queue{
    Node *head;
    Node *tail;
}//got a doubly queue

现在要推送一个元素:

void queue_push(queue *q,int value)
{
    Node *n=(Node*)malloc(sizeof(Node));
    n->val=value;
    n->prev=NULL;
    if(q->head==NULL && q->tail==NULL)
    {
        n->next=NULL;
        q->head=n
        q->tail=n;
    }
    else
    {
        n->next=q->head;
        n->head->prev=n;
        q->head=n;
    }
}

如果我帮助你学习新的东西,我现在不知道,但是任何方式都不能尝试这一点,我认为它会起作用。

答案 1 :(得分:0)

以下是我的问题的答案:

void queue_push(struct queue **q, void *p) {
    struct queue *tmp = malloc(sizeof(struct queue));
    tmp->val = p;
    if(*q)
    {
        tmp->next = (*q)->next;
        (*q)->next = tmp;
    }
    else
        tmp->next = tmp;
    *q = tmp;
}

如果有兴趣的话,我也会给你queue_pop,随意使用!

void* queue_pop(struct queue **q) {
    struct queue *tmp = (*q)->next;
    void *x = tmp->val;
    if(tmp == tmp->next)
        *q = NULL;
    else
        (*q)->next = tmp->next;
    free(tmp);
    return x;
}
相关问题