Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
10void GetNthTest() {<strong>List</strong> my<strong>List</strong> = BuildOneTwoThree(); // build {1, 2, 3}int lastNode = GetNth(my<strong>List</strong>, Length(my<strong>List</strong>)-1); // returns the value 3}Essentially, GetNth() tries to make the list appear like an array — the client can ask forelements by index number. However, GetNth() is much slower than [ ] for an array. Theadvantage of the linked list is its much more flexible memory management — we canPush() at any time to add more elements and the memory is allocated as needed.// Given a list and an index, return the data// in the nth node of the list. The nodes are numbered from 0.// Assert fails if the index is invalid (outside 0..lengh-1).int GetNth(struct node* head, int index) {// Your code3 — Delete<strong>List</strong>()Write a function Delete<strong>List</strong>() that takes a list, deallocates all of its memory and sets itshead pointer to NULL (the empty list).void Delete<strong>List</strong>Test() {<strong>List</strong> my<strong>List</strong> = BuildOneTwoThree(); // build {1, 2, 3}}Delete<strong>List</strong>(&my<strong>List</strong>); // deletes the three nodes and sets my<strong>List</strong> to NULLPost Delete<strong>List</strong>() Memory DrawingHere's the drawing showing the state of memory after Delete<strong>List</strong>() executes in the abovesample. Overwritten pointers are shown in gray and deallocated heap memory has an 'X'through it. Essentially Delete<strong>List</strong>() just needs to call free() once for each node and set thehead pointer to NULL.StackHeapDelete<strong>List</strong>Test()my<strong>List</strong>my<strong>List</strong> isoverwrittenwith thevalue NULL.1 2 3The three heap blocks are deallocated by calls tofree(). Their memory will appear to be intact fora while, but the memory should not beaccessed.