0

我有这个代码来打印链接列表 [1,2,3]

    void reverse(struct node *ptr){
          head = ptr;
          while(ptr!=NULL){

              printf("%d--->",ptr->data);

              ptr=ptr->next;
          }   
  }

输出: 1-->2-->3

我正在尝试打印ptr(当前节点)的下一个元素,例如

 void reverse(struct node *ptr){
              head = ptr;
              while(ptr!=NULL){

                  printf("%d--->",ptr->data);

                  ptr=ptr->next;
                      printf("%d--->",ptr->data);
              }   
      }

为什么不打印1-->2-->2-->3-->3

4

3 回答 3

1

你可能想改变这个

  ptr=ptr->next;
  printf("%d--->",ptr->data);

成为

 ptr=ptr->next;
 if (NULL != ptr)
   printf("%d--->",ptr->data);

对于最后一次迭代,程序尝试取消引用NULL,这会导致未定义的行为,这反过来又很可能导致程序崩溃。

由于stdout是行缓冲,填充的缓冲区1-->2-->2-->3将不再被刷新和打印出来。


您可能有机会通过添加

flush(stdout);

每次调用print().

于 2013-08-20T19:18:21.630 回答
1
void reverse(struct node *ptr){
              head = ptr;
              while(ptr!=NULL){

                  printf("%d--->",ptr->data);

                  ptr=ptr->next;
                  if (ptr)
                      printf("%d--->",ptr->data);
              }   
      }

试试这个代码。问题是 ptr 在循环期间的某个时刻将等于NULL,但是您在printf("%d--->",ptr->data);分配ptr. 就像 :printf("%d--->",NULL->data);这会导致未定义的行为(您可能会遇到分段错误)。

于 2013-08-20T19:19:01.177 回答
1

使用第二个代码,您将遇到分段错误。

因为在这段代码中

ptr=ptr->next;

where ptr->nextis NULL, then ptrwill beNULL然后执行

printf("%d--->",ptr->data);

with ptr=NULL会导致分段错误

于 2013-08-20T19:20:39.587 回答