【发布时间】:2020-07-21 03:33:47
【问题描述】:
我正在尝试打印一个双端队列 (deque),它也是一个 const。我的双端队列结构很简单:
struct node {
int item;
struct node *previous;
struct node *next;
};
struct deque {
struct node *start;
struct node *end;
};
我的看法如下:
void deque_print(const struct deque *deq) {
assert(deq);
if (deq->start->item == deq->end->item) {
printf("[%d]\n", deq->front->item);
}
else {
printf("{");
while (1) {
printf("%d", deq->start->item);
deq->start = deq->start->next; /// I know this is the problem
printf(" ");
}
printf("}\n");
}
}
正如代码 cmets 中所述,我知道是哪一行导致了问题(因为 deq 的类型是 const)。我想知道如何改进它以便可以打印。也请不要更改函数头/声明。
此外,该功能正在打印所有元素,从前到后。它被大括号包围,每个元素之间都有一个空格。因此,如果从前到后的元素是 1、2、3、4、5,那么输出应该是:
{1 2 3 4 5}
另外,不要担心双端队列是空的,我知道该怎么做。我很好奇双端队列至少有 1 个元素。
针对第一条评论,我尝试了:
else {
printf("{");
struct llnode *temp = deq->start;
while (1) {
printf("%d", temp->item); /// problem
temp = temp->next;
if (temp == NULL) break;
printf(" ");
}
printf("}\n");
}
它仍然没有工作。我的打印功能在这里给我带来了问题
【问题讨论】:
-
只需在循环外创建一个临时的
struct deque* temp = deq->start;并将其用作temp = temp->next; -
我试过了,但没有用。我也在上面进行了编辑,所以你可以看到我做了什么。
-
你应该强调什么没用?有错误吗?是否存在分段错误?等
-
我相信这是一个分段错误,但我修复了它。我使用了您的建议,但我在 while 循环中的条件不正确。所以,我改变了它,它现在可以工作了。