/* // Lesson 13, pointers and dynamic memory // // // lists of nodes should look like this // // [data]->[data]->[data]->[data]->[data]->NULL // // in this exercise you will implement functions to add nodes to the end of the list // and remove nodes from the end of the list. // // the data in this exercise are simple ints. when creating new nodes use the getnum() function to fill the data. // // when everything works you should be able to add as many elements as you want, and remove elements back to zero. // // Fun Fact: this is a more simple version of an excercise you will be required to do one day in any programming course and many interviews. // */ #include ///////////////////////////////// //define objects here struct node { int data; node* next; }; ////////////////////////////////// //place function declarations here void insert(node** root); void remove(node** root); void display(node* root); int getsize(node* root); int getnum(); ////////////////////////////////// //main program (do not modify) int main(int argc, char** argv) { bool done = false; node* list = NULL; while( !done ) { int choice; std::cout<<"\n\n========choices========\n"; std::cout<<"1. add a random number to the end of the list\n"; std::cout<<"2. remove a number from the end of the list\n"; std::cout<<"3. display the list\n"; std::cout<<"4. display the size of the list\n"; std::cout<<"0. quit\n"; std::cout<<"please choose an option: "; std::cin>>choice; std::cout<<"\n--------------------------\n"; switch(choice) { case 0: done = true; break; case 1: insert(&list); break; case 2: remove(&list); break; case 3: display(list); break; case 4: std::cout<<"the list size is "<next; delete list; list = next; } return 0; } ////////////////////////////////// //place function definitions here void insert(node** root) { //TODO: your code here node* temp = *root; if(*root) { while((*root)->next) { (*root) = (*root)->next; } (*root)->next = new node; (*root)->next->data = getnum(); (*root)->next->next = 0; *root = temp; } else { (*root) = new node; (*root)->data = getnum(); (*root)->next = 0; } } void remove(node** root) { //TODO: your code here node* temp = *root; node* previous = 0; if(*root) { while((*root)->next) { previous = *root; *root = (*root)->next; } delete *root; *root = temp; if(previous) { previous->next = 0; } } else { std::cout<<"cannot delete items from empty list\n"; } } void display(node* root) { //TODO: your code here if(root) { while(root) { std::cout<data<<"\n"; root = root->next; } } else { std::cout<<"list is currently empty\n"; } } int getsize(node* root) { int size = 0; //TODO: your code here if(root) { while(root) { ++size; root = root->next; } } else { return 0; } return size; } #include int getnum() { return rand()%100; }