【问题标题】:Method to Reverse a Linked list in c++在 C++ 中反转链表的方法
【发布时间】:2014-06-24 05:35:56
【问题描述】:

我正在编写一种在 C++ 中反转链表的方法。我正在尝试使用 Node* 而不是 void 返回类型,但遇到了许多错误。

我的方法代码..

  Node* Reverse(Node *head)
   {
     struct node* prev   = NULL;
     struct node* current = head;
     struct node* next;
     while (current != NULL)
      {
        next  = current->next; 
        current->next = prev;  
        prev = current;
        current = next;
      }
        head = prev;
   }

我收到的编译时错误消息..

    solution.cc: In function 'Node* Reverse(Node*)':
    solution.cc:24:22: error: cannot convert 'Node*' to 'Reverse(Node*)::node*' in initialization
  node* current = head;
                  ^
    solution.cc:28:24: error: invalid use of incomplete type 'struct Reverse(Node*)::node'
     next  = current->next; 
                    ^
    solution.cc:23:14: error: forward declaration of 'struct Reverse(Node*)::node'
   struct node* prev   = NULL;
          ^
    solution.cc:29:16: error: invalid use of incomplete type 'struct Reverse(Node*)::node'
     current->next = prev;  
            ^
    solution.cc:23:14: error: forward declaration of 'struct Reverse(Node*)::node'
   struct node* prev   = NULL;
          ^
    solution.cc:33:10: error: cannot convert 'Reverse(Node*)::node*' to 'Node*' in assignment
 head = prev;
      ^
    solution.cc:34:1: error: no return statement in function returning non-void [-Werror=return-type]
   }
   ^
    cc1plus: some warnings being treated as errors

【问题讨论】:

  • nodeNode的定义是什么?
  • 1 问题是你在这个方法之前一定没有完全声明struct node,你可能只是像struct node一样放了一个前向声明;请附上完整的声明。您还说您的函数将返回类型 o Node* 但您不返回任何内容。
  • 您无需在任何地方输入struct

标签: c++ pointers return-type singly-linked-list


【解决方案1】:

Nodenode 不同,您缺少 return 语句

Node* Reverse(Node *head)
{
 struct Node* prev   = NULL;
 struct Node* current = head;
 struct Node* next;
 while (current != NULL)
  {
    next  = current->next; 
    current->next = prev;  
    prev = current;
    current = next;
  }
    head = prev;
   return head;
}

【讨论】:

    【解决方案2】:

    它应该是节点而不是节点。另外,您还必须返回 Node* 类型的内容。

    Node* Reverse(Node *head)
    {
      struct Node* prev   = NULL;
      struct Node* current = head;
      struct Node* next = new Node;   //new node;
      while (current != NULL)
      {
        next  = current->next; 
        current->next = prev;  
        prev = current;
        current = next;
      }
        head = prev;
    
       return head;          //return head as it will return the whole list.
    
     }
    

    【讨论】:

    • 为什么会出现无故内存泄漏?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-30
    • 2016-03-19
    • 2021-06-27
    • 1970-01-01
    • 2017-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多