Home > Net >  structure not created for Node but at time of initializing a node if we write struct before it ,the
structure not created for Node but at time of initializing a node if we write struct before it ,the

Time:10-08

class Node
{
public:
    int value;
    Node *next;
};
class LinkedList
{
private:
    Node *head;

public:
    LinkedList(void) { head = NULL; }
    ~LinkedList(void){};
    void insertAtHead(int);
    void insertAtLocation(int, int);
    void Delete(int);
    void displayList();
    int countList();
};
void LinkedList::insertAtHead(int new_value)
{
    struct Node *newNode, *NodePtr = head;
    newNode = new Node;
    newNode->value = new_value;
    newNode->next = NULL;
    if (!head)
        head = newNode;
    else
    {
        newNode->next = NodePtr;
        head = newNode;
    }
    cout << "Node successfully inserted at the head\n\n";
}

I didn't create any structure for the node, rather I made a class for it. But I don't know why my code is working properly when I make a newNode in the insertAtHead function by writing struct at the start of initialization, What is happening there? no, compile and run time error when the struct is written before Node. What is the concept behind this work?

CodePudding user response:

There is no difference between struct and class that is relevant to this code. So you can switch them around as you wish with no consequences.

CodePudding user response:

This

struct Node *newNode, *NodePtr = head;

is a C-ism. In C you would write:

Node *newNode, *NodePtr = head;

Moreover a struct is a class in C . struct and class are just two different keywords. Only for default access they make a difference when used to define a class. See here for more details on that: When should you use a class vs a struct in C ?.

  • Related