Home > Software engineering >  Can someone point out the problem in my linked list implementation?
Can someone point out the problem in my linked list implementation?

Time:05-08

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 .

CodePudding user response:

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

  • Related