// Template Version of Link List Toolkit #ifndef LINK2_H #define LINK2_H #include // Provides size_t template struct Node { Item data; Node *link; }; template size_t list_length(Node* headp) { Node *cursor; size_t answer; answer = 0; for(cursor = headp; cursor != NULL; cursor = cursor->link) answer++; return answer; } template void list_head_insert(Node*& headp, const Item& new_item) { Node *insert_ptr; insert_ptr = new Node; insert_ptr->data = new_item; insert_ptr->link = headp; headp = insert_ptr; } template void list_insert(Node* previous_ptr, const Item& new_item) { Node *insert_ptr; insert_ptr = new Node; insert_ptr->data = new_item; insert_ptr->link = previous_ptr->link; previous_ptr->link = insert_ptr; } template Node* list_search(Node* headp, const Item& target) { Node *cursor; for (cursor = headp; cursor != NULL; cursor = cursor->link) if (cursor->data == target) return cursor; return NULL; } template Node* list_locate(Node* headp, SizeType position) { Node *cursor; size_t i; assert(position > 0); cursor = headp; for(i = 1; (i != position) && (cursor != NULL); i++) cursor = cursor->link; return cursor; } template void list_head_remove(Node*& headp) { Node *remove_ptr; remove_ptr = headp; headp = headp->link; delete remove_ptr; } template void list_remove(Node* previous_ptr) { Node *remove_ptr; remove_ptr = previous_ptr->link; previous_ptr->link = remove_ptr->link; delete remove_ptr; } template void list_clear(Node*& headp) { while (headp != NULL) list_head_remove(headp); } template void list_copy(Node* srcPtr, Node*& headp, Node*& tail_ptr) { headp = NULL; tail_ptr = NULL; if (srcPtr == NULL) // Handle empty list return; // Make the head node for the newly created list, and put data in it list_head_insert(headp, srcPtr->data); tail_ptr = headp; // Copy the rest of the nodes one at a time, adding at the tail of new list for (srcPtr = srcPtr->link; srcPtr != NULL; srcPtr = srcPtr->link) { list_insert(tail_ptr, srcPtr->data); tail_ptr = tail_ptr->link; } } template void list_piece (Node* startp, Node* endp, Node*& headp, Node*& tailp) { headp = NULL; tail_ptr = NULL; if (startp == NULL) return; // Make the head node for the newly created list, and put data in it list_head_insert(headp, startp->data); tail_ptr = headp; if (startp == endp) return; // Copy the rest of the nodes one at a time, adding at the tail of new list for (startp = startp->link; startp != NULL; startp = startp->link) { list_insert(tailp, startp->data); tailp = tailp->link; if (startp == endp) return; } } #endif