【问题标题】:Implementation of Queues in Linked Lists链表中队列的实现
【发布时间】:2018-05-17 07:53:56
【问题描述】:

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

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 是前面,但是我认为这可能是问题所在。非常感谢所有帮助。谢谢!

【问题讨论】:

  • 你是如何运行代码的?你在哪里调用 intqueue_construct?
  • “我假设queue->rear->next 是前面”是可疑的。如果queue == NULLqueue->rear == NULL 代码中断。什么都不做。
  • 由于 intqueue_t 只有一个尾部和大小,所以我不知道在调用前面时使用什么,因为它是一个循环队列,并且后面的下一个值会回到前面。

标签: c linked-list queue


【解决方案1】:

你的问题出现在这一行:

if(queue->rear->next == NULL) {

第一次调用该函数时,queue->rear 为 NULL。因此,当您尝试取消引用它以获取 queue->rear->next 时,您会收到运行时错误。

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

编辑

为了解决您的评论,以下是如何以图形方式考虑包含三个元素的列表:

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

queue-&gt;rear 指向element3。因此,要插入第四个元素,您需要使queue-&gt;rear 指向element4 并且element4-&gt;rear 需要指向element1。请记住element 的位置存储在rear-&gt;next 中。

【讨论】:

  • 有人告诉我,对于这段代码,在循环链表中,尾节点(队列后面的节点)指向头节点(队列前面的节点) .我们不需要变量front。
  • 哦,好吧,这有点不寻常,但我想这是一个很好的练习。我回答的第一部分仍然回答了你的问题。我将更新后半部分以反映循环链表。
  • 该代码适用于队列不为空时为空的情况,我得到另一个运行时错误。 queue-&gt;rear-&gt;next=p; } queue-&gt;rear=p; queue-&gt;size++; }
  • 您需要将p-&gt;next 分配给某些东西,这就是我在提示中所暗示的。你认为它应该指向什么?
  • p-&gt;next = queue-&gt;rear?
猜你喜欢
  • 2011-06-28
  • 1970-01-01
  • 1970-01-01
  • 2012-05-15
  • 1970-01-01
  • 2021-05-20
  • 2020-04-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多