Structure type variable inside structure class.

what does struct ListNode* next; mean? I took the struct out it is still working.
Also, what does newNode->next = NULL;mean?
what is the concept of this?

Thank you.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class FloatList
{
	struct ListNode
	{
		double value;
		struct ListNode* next;
	};
	ListNode* head; // Declare a pointer ot serve as the list head
public:
	FloatList() { head = NULL; } // Constructor initializes the head pointer to NULL
	// This establishes an empty linked list
	void appendNode(double);
	void insertNode(double);
	void deleteNode(double); // Will add in with the next example program
	void displayList();
};


1
2
3
4
5
6
7
8
9
10
void FloatList::appendNode(double num)
{
	ListNode* newNode, *nodePtr; // Allocate a new node & store num
	// The newNode pointer will be used to allocate and point to the new node.
	// nodePtr will be used to travbel down the linked list, looking for the
	// last node
	newNode = new ListNode; // These 3 stmts create a new node and
	newNode->value = num; // store num in its value member
	newNode->next = NULL; // This node will become the last node in the list,
	// so it's next ptr must be set to NULL 
Last edited on
struct ListNode* next; is a struct that holds information about a node: its value and a pointer to the next node in the list.

You can picture a node as a card separated in two halves. On one of the two is written a value e.g. 5 and on the other half you have the information which indicates which card is next. In this case it's a pointer.

newNode->next = NULL; If a node points to NULL it means it points to nothing, therefore it is the last node in your list. it goes like this:

firstNode -> secondNode -> [...] -> lastNode -> NULL
value = 2 ---- value = 5 -------------value = 9

In this example, the first node has a value of 2 and points to secondNode, the second node has a value of 5 and points to the next node. the last node has a value of 9 and because it is the last node, it points to NULL.

Hope this helps


EDIT: Here's a link that explains pretty well how linked lists work : http://www.cplusplus.com/articles/LACRko23/

Last edited on
Topic archived. No new replies allowed.