-1
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?

  • I write this off as Interesting. Looks like the C++ compiler is completely ignoring the `struct` in `struct Node *newNode, *NodePtr = head;`. It's not needed, so it appears the compiler just read it and dropped it into the "Don't care." pile. – user4581301 Oct 07 '21 at 19:09

2 Answers2

1

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.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
0

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++?.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185