int main() { node *head = NULL; int i, n, data, t; printf("Enter the list length: "); scanf("%d", &n); printf("length of list: %d\n", n); for (i = 0; i < n; ++i) { scanf("%d", &data); printf("Entered value: %d\n", data); push(&head, data); } printf("Printing all the values: \n"); node *ptr = head; while(ptr != NULL) { printf("%d\n", ptr -> data); ptr = ptr -> next; } ptr = head; printf("The length of list: %d\n", length(ptr)); ptr = head; printf("The length of list: %d\n", lengthUsingPointerToPointer(&ptr)); scanf("%d", &t); ptr = head; printf("Nth node: %d\n", getNthNode(&ptr, t)); return 0; }
void List::insert( ElementType dataVal, int index ){ if (index < 0|| index > mySize) { std::cerr<<"Index out of range. Nothing inserted"<<std::endl; return; } if (empty()){ NodePointer ptr = new Node(dataVal); ptr->next = first; first = ptr; }else{ NodePointer newptr = new Node(dataVal); NodePointer predptr = getNthNode(index - 1); newptr->next = predptr->next; //reassign the previous pointer unless the new node is going in the front if (index >0) predptr->next = newptr; if (index == 0){ first = newptr; newptr->next = predptr; if (mySize==1) predptr->next = 0; } } mySize++; }
/* Remove the value from this List at a given index. Precondition: The list is not empty and index is valid (0 <= index < the list size). Postcondition: the element at position index has been removed (provided index is a legal position). */ void List::erase( int index ){ if (index < 0|| index > mySize) { std::cerr<<"Index out of range. Nothing deleted"<<std::endl; return; } if ( mySize== 0) { std::cerr<<"List is Empty. Nothing to delete"<<std::endl; return; } NodePointer eraseptr = getNthNode(index); if (index ==0) { first = first->next; delete eraseptr; }else{ NodePointer predptr = getNthNode(index -1); predptr->next =eraseptr->next; delete eraseptr; } mySize--; }