简体   繁体   English

有人可以指出我的链表实现中的问题吗?

[英]Can someone point out the problem in my linked list implementation?

When I compile the following code, I get compile error that " head does not name a type".当我编译下面的代码时,出现“head does not name a type”的编译错误。 Can someone explain what goes wrong?有人可以解释出什么问题了吗?

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

I cannot figure out why am i getting the error.我不知道为什么会收到错误消息。 Please someone help me out.请有人帮助我。

Only declarations are allowed outside of functions.只允许在函数外声明。 Expressions such as head->next = node(4) need to be inside a function. You should move that code into main() . head->next = node(4)等表达式需要在 function 中。您应该将该代码移至main()中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM