text cover

Data Abstraction and Problem Solving with C++

Walls and Mirrors

by Frank M. Carrano

Addison Wesley Logo

ListT.cpp

Go to the documentation of this file.
00001 
00019 #include <cstddef>  // for NULL
00020 #include <new>      // for bad_alloc
00021 
00022 using namespace std;
00023 
00024 template <typename T>
00025 List<T>::List(): size(0), head(NULL)
00026 {
00027 }  // end default constructor
00028 
00029 template <typename T>
00030 void List<T>::insert(int index, const T & newItem)
00031    throw(ListIndexOutOfRangeException, ListException)
00032 {
00033    int newLength = getLength() + 1;
00034 
00035    if ((index < 1) || (index > newLength))
00036       throw ListIndexOutOfRangeException(
00037     "ListIndexOutOfRangeException: insert index out of range");
00038    else
00039    {  // create new node and place newItem in it
00040       try
00041       {  ListNode<T> *newPtr = new ListNode<T>;
00042          size = newLength;
00043     newPtr->item = newItem;
00044 
00045     // attach new node to list
00046     if (index == 1)
00047     {  // insert new node at beginning of list
00048        newPtr->next = head;
00049        head = newPtr;
00050     }
00051     else
00052     {  ListNode<T> *prev = find(index-1);
00053             // insert new node after node
00054             // to which prev points
00055             newPtr->next = prev->next;
00056        prev->next = newPtr;
00057     }  // end if
00058       }
00059       catch (bad_alloc e)
00060       {
00061     throw ListException(
00062        "ListException: insert cannot allocate memory");
00063       }  // end try
00064    }  // end if
00065 }  // end insert
00066 
00067 template <typename T>
00068 ListNode<T> *List<T>::find(int index) const
00069 {
00070    if ( (index < 1) || (index > getLength()) )
00071       return NULL;
00072    else  // count from the beginning of the list
00073    {  ListNode<T> *cur = head;
00074       for (int skip = 1; skip < index; ++skip)
00075          cur = cur->next;
00076       return cur;
00077    }  // end if
00078 }  // end find

Generated on Sun Aug 27 20:00:20 2006 for AWLogo by  doxygen 1.4.6