【问题标题】:Printing a const deque structure打印一个 const deque 结构
【发布时间】: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 循环中的条件不正确。所以,我改变了它,它现在可以工作了。

标签: c printf deque


【解决方案1】:

首先,您应该保存双端队列长度并在 while 循环中使用它,否则您将遇到 segFault,因为while(1) 会永远迭代。其次,我建议您使用时间节点作为迭代器,因为一旦打印双端队列,您将丢失起始节点。

void deque_print(const struct deque *deq) {
  int i = 0;
  node *tmp_node = deq->start;
  printf("{");
  while (i < deq->length) { //assuming you have the variable in the struct
    printf("%d", tmp_node->item);
    tmp_node = tmp_node->next;
    printf(" ");
    i++;
  }
  printf("}\n");
  }
}

【讨论】:

  • 很遗憾,我无法修改deque或llnode的结构。我需要以某种方式不断更新它,直到我认为达到 NULL。我在上面编辑了我的问题,以展示我尝试过的另一种方法。
  • 但是给你带来了什么问题?段错误或数字顺序错误。
  • 实际上,我意识到我已经修复了它。我在更新编辑中的错误是我不应该检查 temp == NULL 的时间,而是 temp-&gt;item == deq-&gt;end-&gt;item 的时间。无论如何,我感谢您的支持!
  • 如果您在其他节点中重复了数字,那将无法正常工作。
  • 嗯,你是对的。感谢那。我再次更改为if (temp == deq-&gt;end) break;。现在,它似乎适用于重复的数字。
【解决方案2】:
void deque_print(const struct deque *deq)
{
    if (deq == NULL)
    {
        printf("{}");
        return;
    }

    const struct node *node = deq->start;
    const struct node *end = deq->end;

    printf("{");
    while (node)
    {
        if (node == end)
        {
            printf("%d", node->item);
        }
        else
        {
            printf("%d ", node->item);
        }
        node = node->next;
    }
    printf("}");
}

【讨论】:

    猜你喜欢
    • 2011-07-18
    • 2015-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-24
    • 2021-07-12
    相关资源
    最近更新 更多