Cyrus Lee
Cyrus Lee

Reputation: 27

Linked Lists: structure inside a structure?

I'm still kind of new in terms of working with Linked lists in C++. I was looking through my textbook and found this header file under the linked lists section.

//Specifcation file for the NumberList class
#ifndef NUMBERLIST_H
#define NUMBERLIST_H

class NumberList
{
private:
  //Declare a structure for the list
  struct ListNode
  {
     double value;         //The value in this node 
     struct ListNode *next;  //To point to the next node 
  };

  ListNode *head;      //List head pointer
public:
  //Constructor 
  NumberList();
   { head = nullptr; }

  //Destructor 
  ~NumberList();

  //Linked list operations
  void appendNode(double);
  void insertNode(double);
  void deleteNode(double);
  void displayList() const;
};
#endif

So I am wondering what exactly is happening on the line where it says struct ListNode *next; It seems to be a pointer, so why do we have to include the "struct" part on this pointer? I was confused at first because I thought it was a struct inside of another struct.

Can someone please explain this to me?

Upvotes: 0

Views: 597

Answers (1)

biqarboy
biqarboy

Reputation: 852

So I am wondering what exactly is happening on the line where it says struct ListNode *next;

As you mentioned later, it is a pointer that points to the next block of the struct ListNode. Check the following figure. The ListNode consists of Data and Next here. The Next is a pointer that points to the next ListNode cell.

It seems to be a pointer, so why do we have to include the "struct" part on this pointer?

It is C-style declaration. In C, struct names are in their own namespace. In C++ you do not need this. You are seeing it here because C++ also support C-style declaration in this case. You can check my edited code here. I removed the the struct part from the next pointer declaration inside the ListNode structure and it works fine.

#include <iostream>

using namespace std;

class NumberList
{
private:
  //Declare a structure for the list
  struct ListNode
  {
     double value;         //The value in this node 
     ListNode *next;  //To point to the next node 
  };

  ListNode *head;      //List head pointer
public:
  //Constructor 
  NumberList() { head = nullptr; }
  
  NumberList(double val) {
      head = new ListNode();
      head->value = val;
  }

  //Destructor 
  ~NumberList();

  //Linked list operations
  void appendNode(double);
  void insertNode(double);
  void deleteNode(double);
  void displayList() {
      ListNode *curr = head;
      while(curr != nullptr) {
          cout << curr->value << " ";
          curr = curr->next;
      }
      cout << endl;
  }
};

int main()
{
    NumberList *nl = new NumberList(5.0);
    nl->displayList();
    return 0;
}

Upvotes: 1

Related Questions