在c ++中反转链接列表的方法

时间:2014-06-24 05:35:57

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

我正在编写一种方法来反转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

2 个答案:

答案 0 :(得分:2)

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;
}

答案 1 :(得分:-1)

它应该是Node而不是node。另外你必须返回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.

 }