// ------------------------------------------------------------------------- // System Headers // ------------------------------------------------------------------------- #include #include // ------------------------------------------------------------------------- // Typedefs // ------------------------------------------------------------------------- typedef struct _Node { struct _Node *mNext; int mValue; } Node; // ------------------------------------------------------------------------- // freeList - Free the linked list starting with 'head' // ------------------------------------------------------------------------- static void freeList(Node *head) { Node *current = head; while(current) { Node *tmp = current->mNext; printf("freeing: [%p]\n", current); free(current); current = tmp; } } // ------------------------------------------------------------------------- // makeNode - Dynamically allocate and return a Node with value 'value' // ------------------------------------------------------------------------- static Node *makeNode(int value) { size_t size = sizeof(Node); Node *ptr = malloc(size); if(!ptr) { printf( "[%s | %d] - Could not allocate: %lu bytes\n", __FILE__, __LINE__, size ); exit(1); } printf("allocated: [%p]\n", ptr); ptr->mValue = value; ptr->mNext = NULL; return(ptr); } // ------------------------------------------------------------------------- // makeList - Create and return a linked list of Nodes // ------------------------------------------------------------------------- static Node *makeList() { Node *head = NULL; Node *current = NULL; int i = 0; while(i <= 10) { Node *theNode = makeNode(i++); if(!head) { current = head = theNode; } else { current->mNext = theNode; current = current->mNext; } } return(head); } // ------------------------------------------------------------------------- // reverse - Reverse the list starting with 'head', return the new head // of the list. // ------------------------------------------------------------------------- static Node *reverseList(Node *head) { Node *current = NULL; Node *ptr = head; while(ptr) { Node *next = ptr->mNext; ptr->mNext = current; current = ptr; ptr = next; } return(current); } // ------------------------------------------------------------------------- // dumpList - Output the linked list's contents to the console // ------------------------------------------------------------------------- static void dumpList(Node *head) { Node *ptr = head; while(ptr) { printf("[%p] => %d\n", ptr, ptr->mValue); ptr = ptr->mNext; } } // ------------------------------------------------------------------------- // main // ------------------------------------------------------------------------- int main() { Node *list = makeList(); printf("\n"); dumpList(list); printf("\n"); Node *reversed = reverseList(list); dumpList(reversed); printf("\n"); freeList(reversed); return(0); }