| FIND the location of insertion before you can insert the element. |
That is because head points to the first element of the list...
So you do NOT need to find the insert location :-)
| Creating variables is reserve some unused memory for storage |
New list elements can be created (new memory reserved) and then linked into an existing list
new TYPE; |
NOTE: Don't be surprised that an operator returns an address.
In fact, you have seen such an operator before:
&(variable) returns the address of variable |
NOTE: since new TYPE returns an address of type TYPE, we must store the return value in a variable of the reference type:
TYPE *ptr;
|
class ListElem
{
int value;
ListElem *next;
};
ListElem *p; // p will receive the address
p = new ListElem;
p->value = 1234;
p->next = ...;
|
|
ListElem head = NULL;
|
Assume:
head = start of linked list (or NULL for empty list)
|
|
|
|
|
|
|
|
class ListElem
{
public:
int value; // Integer
ListElem *next; // Pointer used to make link
};
int main(int argc, char *argv[])
{
ListElem *head, *elem;
// Empty list
head = NULL;
// Insert first element
elem = new ListElem;
elem->value = 1500;
elem->next = head;
head = elem;
// Insert second element
elem = new ListElem;
elem->value = 1234;
elem->next = head;
head = elem;
}
|
Well, insert a new list element at head is a well-defined task
|
NOTE: we assume that the value in the list element has already been initialized (that is NOT part of the insert algorithm !)
|
NOTE: there are 2 ways to return the head value:
|
class ListElem
{
public:
int value;
ListElem *next;
};
ListElem * InsertAtHead(ListElem * head, ListElem * elem)
{
elem->next = head; // Make new list element points
// to the start of "old list"
return(elem); // Return the new head
}
|
int main(int argc, char *argv[])
{
ListElem *head, *p;
head = NULL; // Empty list
p = new ListElem;
p->value = 1500;
head = InsertAtHead(head, p); // <--- record the new head in "head"
}
|
class ListElem
{
public:
int value;
ListElem *next;
};
// The "head" variable is BOTH input and output variable !
void InsertAtHead(ListElem * & head, ListElem * elem)
{
elem->next = head; // Make new list element points
// to the start of "old list"
head = elem; // Make link AND return NEW head value
}
|
NOTE: The head parameter MUST be passed by-reference
(Otherwise, the function CANNOT change the variable head in main's scope !!!)
int main(int argc, char *argv[])
{
ListElem *head, *p;
head = NULL; // Empty list
p = new ListElem;
p->value = 1500;
InsertAtHead(head, p); // <--- pass "head" by reference
}
|