c - 循环链表中的队列

标签 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,它会在“(*q)->next = tmp;”处告诉我“Illegal instruction (core dumped)”而且我不知道我哪里出了问题。

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

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

树结构很简单:

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

最佳答案

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

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

我现在不知道我是否能帮助您学习新东西,但不管怎样,如果您不介意尝试一下,我认为它会奏效。

关于c - 循环链表中的队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33720296/

相关文章:

c - 链表程序

java - 当项目排队到队列对象上时,队列对象保持为空

c - C 中的 BFS 实现抛出段错误

c - 请求提示 : Possibilities to log files from a router to a server

c - 为什么 sizeof 在尚未存在的变量上成功?

c - 如何将文本与终端中心对齐?

c - 在c中声明空字符串变量

java - 一个带有一个参数的构造函数创建两个不同的对象

java - 在Java中反转链表而不改变原始链表

php - 关于排队系统的问题