我正在编写一种方法来反转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
答案 0 :(得分:2)
Node
与node
不同,您遗漏了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.
}