【问题标题】:Reversing Linked List with Function用函数反转链表
【发布时间】:2017-04-24 04:47:52
【问题描述】:

我试图通过将头节点传递给函数来反转和打印链表。然后我必须使用“打印输出”功能打印反向列表。打印输出不是问题,但反转让我很困惑。当我尝试运行代码时,我只打印了两次列表

#include <stdio.h>
#include <stdlib.h>

typedef struct node
{
   int number;
   struct node * next;
} Node;

typedef Node * Nodeptr;

void printout(Nodeptr);

int main()
{
   int n;
   Nodeptr head = NULL;
   if((head = malloc(sizeof(Node))) == NULL)
      return 0;
   head->number = 72;
   head->next = NULL;
   Nodeptr here = head;
   Nodeptr newnode = NULL;
   for(n=0; n<100; n++)
   {
     if((newnode = malloc(sizeof(Node))) == NULL)
        return 0;
     newnode->number = rand()%50 + 50;
     newnode->next = NULL;
     here->next = newnode;
     here = here->next;
     //printf("value of cell %d contains %d\n", n, newnode->number);
    }
    printout(head);
    //sum(head);
   void reverse(head);
   printout(head);
   return 0;
}

void printout(Nodeptr head)
{
 int i;
 for(i=0; i<=100; i++)
  {
    if (head->next != NULL)
     {
       printf("value of cell %d contains %d \n",i, head->number);
       head = head->next;
     }
   }
}

/*void sum(Nodeptr head)
{
  int sum = 0;
  do(sum += Nodeptr head);
    while(head->next != NULL);
   printf("Sum of nodes is %d \n", head->next);
}*/

void reverse(Nodeptr head)
{
  Nodeptr current = head;
  Nodeptr prev = NULL;
  Nodeptr next = NULL;
  int i;
    while(current!=NULL)
    {
      //creating these to hold value while
      //we reassign value to ptr's
      next=current->next;
      current->next=prev;
      prev=current;
      current=next;
    }
   head=prev;

}

正如我提到的,给我带来麻烦的是“反向”功能,打印输出成功地显示了 100 个单元格的列表,其中包含指定范围内的随机值。

   void reverse(Nodeptr head)
{
  Nodeptr current = head;
  Nodeptr prev = NULL;
  Nodeptr next = NULL;
  int i;
    while(current!=NULL)
    {
      //creating these to hold value while
      //we reassign value to ptr's
      next=current->next;
      current->next=prev;
      prev=current;
      current=next;
    }
   head=prev;

}

我试图创建三个新节点来帮助我处理这里的指针。 希望这不是一个糟糕的问题,我很感激任何帮助。请注意,“打印输出”已被注释掉,如果您想自己测试此代码,则需要取消注释。顺便说一句,我正在使用代码块。再次感谢。

【问题讨论】:

  • 0) void reverse(head); --> void reverse(Nodeptr head); reverse(head);
  • 1) head=prev; 不更新调用方变量。
  • 2) if (head-&gt;next != NULL) :因一个错误关闭。

标签: c linked-list


【解决方案1】:

主要问题是reverse 还必须交换指向列表头部的指针。但是,使用函数void reverse(Nodeptr head),您按值传递头指针,因此没有机会以影响调用者的方式更改它。

我建议将签名更改为

Nodeptr reverse(Nodeptr head);

并将调用更改为

head = reverse(head);

可能还有其他问题;但这可能是进一步分析的起点。

【讨论】:

    猜你喜欢
    • 2013-07-27
    • 2019-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-31
    • 2019-07-27
    • 2021-05-21
    相关资源
    最近更新 更多