/**************************************************************** * Engineering 4892 Data Structures * Assignment: 3 Date Due: June 14th/2001 * Name: Daryl Martin * Student #: 9713520 * Username: darylm *****************************************************************/ #include "dlist.h" /***************************************************************** * insert - insert a node into a list at the ith position * Pre: 0 <= i <= |L| * Post: L' = L with x inserted at the ith position. * If i == |L| then x is appended *****************************************************************/ template List::Status List::insert(const T& x, int i) { int length = size(); //get the length of the linked list Node *current = head; //declare a pointer to follow the list Node* toAdd; //declare new node if (i < 0 || i > length){ //If fails the pre conditions err = NoSuchElement; } else { if (i == 0){push_front(x);} //if at the beginning of the list else if (i == length){push_back(x);} //if at the end of the list else{ for (int k=0;k < i;k++){ //loop to go to the ith element current = current->next; //in the list } toAdd = new(std::nothrow) Node; if(toAdd != 0){ //check for memory toAdd->prev = current->prev; //These commands configure toAdd->next = current; //the inserted node properly current->prev->next = toAdd; current->prev = toAdd; toAdd->data = x; } else{ //if there isn't enough memory available err=NewFail; } } } return err; } /**************************************************************** * remove - remove the ith element of the list * Pre: 0 <= i < |L| * Post: L' = L with i'th element removed. *****************************************************************/ template List::Status List::remove(int i){ Node *current = head; //create a pointer to follow list int length = size(); //find the lenght of the list if (i < 0 || i > length - 1){ err = NoSuchElement; } //fails preconditions else { if (i == 0){pop_front();} //if the value is at the head else if ( (length - 1) == i){pop_back();} //if the value is at the tail else{ for (int j=0;j < i;j++){ current = current->next; //jump to the end of the linked list } current->prev->next = current->next; //"Jump" over the node we want current->next->prev = current->prev; //to delete with pointers delete current; //delete the current node } } return err; } /**************************************************************** * operator[] - find the data in the ith node * Pre: 0 <= i < |L| * Post: Result = L[i] (i'th element of L) *****************************************************************/ template const T& List::operator[] (int i) const { int length = size(); //find the lenght of the list Node *current = head; //create a pointer to follow the list static T data = 0; //create a null piece of data if (i < 0 || i > (length -1)){ //fail the preconditions err = NoSuchElement; } else{ for(int a=0;anext; //find the node we want to extract info from } data = current->data; } return data; }