C 链表中队列的实现

C 链表中队列的实现,c,linked-list,queue,C,Linked List,Queue,我得到这些结构声明是为了实现使用循环链表的队列集合 typedef struct intnode { int value; struct intnode *next; } intnode_t; typedef struct { intnode_t *rear; // Points to the node at the tail of the // queue's linked list int size;

我得到这些结构声明是为了实现使用循环链表的队列集合

typedef struct intnode {
    int value;
    struct intnode *next;
} intnode_t;

typedef struct {
    intnode_t *rear;   // Points to the node at the tail of the 
                       // queue's linked list
    int size;          // The # of nodes in the queue's linked list
} intqueue_t;

intnode_t *intnode_construct(int value, intnode_t *next)
{
    intnode_t *p = malloc(sizeof(intnode_t));
    assert (p != NULL);
    p->value = value;
    p->next = next;
    return p;
}


/* Return a pointer to a new, empty queue.
 * Terminate (via assert) if memory for the queue cannot be allocated.
 */

intqueue_t *intqueue_construct(void)
{
    intqueue_t *queue = malloc(sizeof(intqueue_t));
    assert(queue != NULL);

    queue->rear = NULL;
    queue->size = 0;
    return queue;
}
我尝试创建一个函数,它将按指定的值排队(将其附加到队列的后部),并且我需要考虑队列是空的两个情况,以及队列中有一个或多个元素时。这是我目前掌握的代码:

void intqueue_enqueue(intqueue_t *queue, int value)
{

    intnode_t *p = intnode_construct(value, NULL);

    if(queue->rear->next == NULL) {
        //the queue is empty
        queue->rear->next =p;
    } else {
        //the queue is not empty
        queue->rear=p;
    }
    queue->rear=p;
    queue->size++;
}

这段代码给了我一个运行时错误,所以我不确定出了什么问题。在代码中,我假设queue->rear->next是前面,但是我认为这就是问题所在。非常感谢您的帮助。谢谢

您的问题发生在这一行:

if(queue->rear->next == NULL) {
第一次调用函数时,queue->rear为空。因此,当您尝试取消引用它以获取
queue->rear->next
时,您会得到运行时错误

要修复此代码,请更新
intqueue\u enqueue
以检查
queue->size==0
,如果是,则需要通过设置
queue->rear=p
p->next=p
对其进行初始化。然后更新
else
子句,以便在两个现有元素之间插入元素。提示:您需要在
p
中存储
queue->rear->next

编辑 为了回应您的评论,以下是如何以图形方式思考包含三个元素的列表:

<element1: next==element2> <element2: next==element3> <element3: next==element1>


queue->rear
指向
element3
。因此,要插入第四个元素,需要使其
queue->rear
指向
element4
element4->rear
需要指向
element1
。请记住,
元素
的位置存储在
后方->下一步

您如何运行代码?你把intqueue结构称为什么?“我假设
queue->rear->next
是前面”是可疑的。如果
queue==NULL
queue->rear==NULL
则代码中断。假设没有。与同一OP之前的问题密切相关:由于intqueue\u不仅有后部和大小,我不确定在调用前部时使用什么,因为它是一个循环队列,后部之后的下一个值将返回到前部。我被告知,对于这段代码,在循环链表中,尾部节点(队列后部的节点)指向头部节点(队列前部的节点)。我们不需要变量front。哦,好吧,这有点不寻常,但我想这是一个很好的练习。我的答案的第一部分仍然回答了你的问题。我将更新下半部分以反映循环链表。该代码适用于队列为空时,当队列不为空时,我会遇到另一个运行时错误。
queue->rear->next=p;}queue->rear=p;queue->size++;}
您需要将
p->next
分配给某个对象,这就是我在提示中所暗示的。您认为它应该指向什么?会
p->next=queue->rear