00001
00019 #include <cstddef>
00020 #include <new>
00021
00022 using namespace std;
00023
00024 template <typename T>
00025 List<T>::List(): size(0), head(NULL)
00026 {
00027 }
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 {
00040 try
00041 { ListNode<T> *newPtr = new ListNode<T>;
00042 size = newLength;
00043 newPtr->item = newItem;
00044
00045
00046 if (index == 1)
00047 {
00048 newPtr->next = head;
00049 head = newPtr;
00050 }
00051 else
00052 { ListNode<T> *prev = find(index-1);
00053
00054
00055 newPtr->next = prev->next;
00056 prev->next = newPtr;
00057 }
00058 }
00059 catch (bad_alloc e)
00060 {
00061 throw ListException(
00062 "ListException: insert cannot allocate memory");
00063 }
00064 }
00065 }
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
00073 { ListNode<T> *cur = head;
00074 for (int skip = 1; skip < index; ++skip)
00075 cur = cur->next;
00076 return cur;
00077 }
00078 }