You need a pointer to the beginning of the list - this is the "root" from which the list grows.
Code:
int main()
{
node *root; // Pointer to the first node
root = new node; // Get memory for the first node.
root->next = 0; // Mark the "next" node as "not there".
root->x = 5; // Fill in the list with some value.
}
However, this is pretty meaningless - that's like saying you have a SET of tools when you have one screwdriver. This is a linked list with one element, which is valid, and one screwdriver is a set of tools too - but very limited.
A more reasonable example:
Code:
#include <iostream>
struct node {
int x;
node *next;
};
int main()
{
node *root; // Pointer to the first node
root = new node; // Get memory for the first node.
root->next = 0; // Mark the "next" node as "not there".
root->x = 5; // Fill in the list with some value.
// Since this is C++, we can introduce new variables later.
node *newNode;
newNode = new node; // Create one more item.
newNode->x = 7; // Set x to 7.
newNode->next = 0; // Mark this as the end.
root->next = newNode; // Insert it after root.
for(int i = 0; i < 3; i++) {
node *current = newNode; // This is the previously inserted node.
newNode = new node; // A further node.
newNode->x = i + 10; // Set x to a something.
newNode->next = 0; // Mark the end.
current->next = newNode; // Insert the node AFTER current.
}
node *temp; // A temporary node pointer.
temp = root; // Set it to the start of the list.
while (temp != 0) { // Check if we are at the end (0), if not, go print the contents of the list
std::cout << "x = " << temp->x << std::endl; // Print the "x" for this node.
temp = temp->next; // Go to the next item in the list.
}
return 0;
}
Output:
Code:
x = 5
x = 7
x = 10
x = 11
x = 12
--
Mats