有人可以指出我的链表实现中的问题吗?
Can someone point out the problem in my linked list implementation?
当我编译以下代码时,出现“head does not name a type”的编译错误。
谁能解释一下哪里出了问题?
#include <iostream>
using namespace std;
/* Link list node */
struct node {
int val;
struct node* next;
node(int x)
{
this->val = x;
next = NULL;
}
};
struct node *head = new node(3);
head -> next = new node(4); // error: head does not name a type.
head -> next->next = new node(5); // error: head does not name a type.
void print(){
struct node* temp = head;
while (temp != NULL) {
cout << temp->val << " ";
temp = temp->next;
}
}
int main()
{
print();
return 0;
}
我不明白为什么会收到错误消息。请有人帮助我。
只允许在函数外声明。 head->next = node(4)
等表达式需要在函数内部。您应该将该代码移至 main()
.
当我编译以下代码时,出现“head does not name a type”的编译错误。 谁能解释一下哪里出了问题?
#include <iostream>
using namespace std;
/* Link list node */
struct node {
int val;
struct node* next;
node(int x)
{
this->val = x;
next = NULL;
}
};
struct node *head = new node(3);
head -> next = new node(4); // error: head does not name a type.
head -> next->next = new node(5); // error: head does not name a type.
void print(){
struct node* temp = head;
while (temp != NULL) {
cout << temp->val << " ";
temp = temp->next;
}
}
int main()
{
print();
return 0;
}
我不明白为什么会收到错误消息。请有人帮助我。
只允许在函数外声明。 head->next = node(4)
等表达式需要在函数内部。您应该将该代码移至 main()
.