Brandon Tiqui
Brandon Tiqui

Reputation: 1439

How do I write a public function to return a head pointer of a linked list?

class Newstring
{
public:
    Newstring();
    void inputChar ( char);
    void display ();
    int length ();
    void concatenate (char);
    void concatenate (Newstring);
    bool substring (Newstring);
    void createList ();
    Node * getHead (); // error
private:
    struct Node
    {
        char item;
        Node *next; 
    };
    Node *head;

};

I am getting a syntax error : missing ';' before '*' on the declaration for my getHead function (yes I can't think of a better name). The purpose of this function is to return the head pointer.

Upvotes: 1

Views: 893

Answers (5)

epatel
epatel

Reputation: 46051

Another way would be to forward declare Node by placing a struct before Node

    :
    void createList ();
    struct Node * getHead ();
private:
    struct Node
    {
        :

Upvotes: 1

Klaim
Klaim

Reputation: 69682

To answer Brandon about keeping the struct in private, or keeping the current code while adding a declaration, the way is :

class Newstring
{
    struct Node; // here the declaration
public:

    Newstring();
    void inputChar ( char);
    void display ();
    int length ();
    void concatenate (char);
    void concatenate (Newstring);
    bool substring (Newstring);
    void createList ();
    Node * getHead (); // error
private:
    struct Node
    {
        char item;
        Node *next; 
    };
    Node *head;

};

Upvotes: 2

Viktor Sehr
Viktor Sehr

Reputation: 13099

You have to declare the Node struct above getHead();

class Newstring
{

public:
    struct Node
    {
        char item;
        Node *next; 
    };
    Newstring();
    void inputChar ( char);
    void display ();
    int length ();
    void concatenate (char);
    void concatenate (Newstring);
    bool substring (Newstring);
    void createList ();
    Node * getHead (); // error
private:

    Node *head;

};

Upvotes: 2

peterchen
peterchen

Reputation: 41106

Declare Node before you use it.

Upvotes: 3

aJ.
aJ.

Reputation: 35460

Node * getHead()

Compiler is not able to get the definition of Node when getHead() is encountered.

  struct Node
    {
        char item;
        Node *next; 
    };

Put the definition of Node before it is used.

class Newstring
{
private:
    struct Node
    {
        char item;
        Node *next; 
    };
    Node *head;
public:
    Newstring(); ...
    Node * getHead (); 

Upvotes: 1

Related Questions