|
/* ========================================================
Insert at head technique:
1. create new list element p
put values in the payload area...
2. make p point to first element in list
3. make head point to new list element
======================================================== */
p = malloc( sizeof(struct ListElem) ); // (1)
p->value = 123; // Payload...
p->next = head; // (2)
head = p; // (3)
|
We just need to put these statements into a function
struct ListElem* insertHead(struct ListElem* head, struct ListElem* elem)
{
elem->next = head; // make "elem" point to "head"
return(elem); // return address of new head
}
|
How to run the program:
|
List delete ( List head )
{
return( head.next ); // Make the second element the new head
}
|
|
free( pointerVariable ) ; |
Effect:
|
int main(int argc, char *argv[])
{
struct BankAccount* p;
p = malloc( sizeof(struct BankAccount) ); // (1)
(*p).accNum = 123; // Long form to access a member variable
p->balance= 400; // Short form to access a member variable
printf("p->accNum = %d p->balance = %f\n", p->accNum, p->balance);
/* ==================================================
Unreserve memory that was allocated at step (1)
================================================== */
free(p);
}
|
|
struct ListElem* deleteHead ( struct ListElem* h )
{
struct ListElem* deleted;
struct ListElem* newHead;
if ( h == NULL )
return(NULL); // Nothing to delete....
deleted = h; // Save the location of the deleted element
newHead = h->next; // We will return this value
free(deleted); // Un-reserve memory cells
return( newHead ); // Make the second element the new head
}
|
How to run the program:
|
I don't want to waste time teaching you deleting from linked list again....
You just apply what you have learned in CS170 to delete the list element; but make sure you save the address (reference) of the deleted element
Then use the free( deleted_element ); statement to un-reserve the memory cells used before the function return.