c - 使用循环链表实现Queue

标签 c data-structures linked-list queue

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

struct node {
    int data;
    struct node *link;
};

void addcll(struct node **, struct node **, int);
void displaycll(struct node *);

void main() 
{
    struct node *front, *rear;

    front = rear = NULL;

    addcll(&front, &rear, 56);
    addcll(&front, &rear, 12);
    displaycll(front);
}

void addcll(struct node **f, struct node **r, int item) {
    struct node *q;
    q = malloc(sizeof(struct node));
    q->data = item;
    if (*f == NULL) {
        *f = q;
    }
    else {
        (*r)->link = q;
        (*r) = q;
        (*r)->link = *f;
    }
}

void displaycll(struct node *f) {
    struct node *q, *p;
    q = f;
    p = NULL;
    while (q != p) {
        printf("%d \n", q->data);
        q = q->link;
        p = f;
    }
}

无法准确找出错误所在,请帮忙! 我也是数据结构的初学者。请给我一些可以学习和实践这些概念的书籍或在线资源的建议

最佳答案

你的addcll是错误的。后指针应始终在队列反推时重置,并且推送的节点的链接应始终设置为front的内容>,即使在添加第一个节点的情况下,顺便说一句。

void addcll(struct node **f, struct node **r, int item) 
{
    struct node *q = malloc(sizeof(struct node));
    q->data = item;
    if (*f == NULL) {
        *f = q;
    }
    else {
        (*r)->link = q;
    }
    (*r) = q; // here
    (*r)->link = *f; // and here.
}

关于c - 使用循环链表实现Queue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58363226/

相关文章:

Java 8 将列表减少为链表

matlab中无法返回零值

符合规范的编译器能否中断 uint32_t -> int16_t -> int32_t 转换?

Java - 偏好的存储结构?

algorithm - 为什么我们需要检测链表中的循环

c - 在C中添加到链表的尾部

c - 如何编写一个程序来查找整型变量的最大值

c - 正则表达式匹配行(换行符除外)(FLEX、BISON)

php - 如何合并两个具有相同结构的Mysql数据库?

java - 有人可以解释为什么/如何更改链接列表中的节点而不直接在 Java 中更改它们吗?