|
|
|
|
|
|
|
void OrdList::InsertTop( /* in */ ComponentType item )
// Precondition:
// component members of list nodes are in ascending order
// && item < component member of first list node
// Postcondition:
// New node containing item is inserted at top of linked list
// && component members of list nodes are in ascending order
{
NodePtr newNodePtr = new NodeType; // Temporary pointer
newNodePtr->component = item;
newNodePtr->link = head;
head = newNodePtr;
} |
|
|
|
|
|
|
|
|
The function precondition states that item must be smaller than the value in the first node. This precondition is not a requirement of linked lists in general. However, the OrdList abstraction we are implementing is an ordered list. The precondition/postcondition contract states that if the client sends a value smaller than the first one in the list, then the function guarantees to preserve the ascending order. If the client violates the precondition, the contract is broken. |
|
|
|
|
|
|
|
|
The following code walk-through shows the steps in inserting a component with the value 20 as the first node in the linked list that was printed in the last section. |
|
|
|
|
|
|
|
|
|
newNodePtr = new NodeType;
newNodePtr->component = item; |
|
|
|
|  |
|
|
|
|
A new node is created. |
|
|
|
 |
|
|
|
|
The number 20 is stored into the component member of the new node. |
|
|
|
| |
|
|
|