【发布时间】: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 == NULL或queue->rear == NULL代码中断。什么都不做。 -
由于 intqueue_t 只有一个尾部和大小,所以我不知道在调用前面时使用什么,因为它是一个循环队列,并且后面的下一个值会回到前面。
标签: c linked-list queue