【发布时间】: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
【问题讨论】:
-
node和Node的定义是什么? -
1 问题是你在这个方法之前一定没有完全声明struct node,你可能只是像struct node一样放了一个前向声明;请附上完整的声明。您还说您的函数将返回类型 o Node* 但您不返回任何内容。
-
您无需在任何地方输入
struct。
标签: c++ pointers return-type singly-linked-list