简体   繁体   中英

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". 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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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