void reverse_recurse(LIST_ITEM ** head) { LIST_ITEM * first; LIST_ITEM * other; if (*head == NULL) { fprintf(stderr, "%s:%d head null\n", __FUNCTION__, __LINE__); return; } first = *head; other = first->next; if (other == NULL) { fprintf(stderr, "%s:%d list is single element\n", __FUNCTION__, __LINE__); return; } reverse_recurse(&other); /* * NULL -- [0] -- [1] -- [2] * f o * f <- o * <- f <- o */ first->next->next = first; first->next = NULL; // reset head *head = other; }
int reverse_recurse(struct Node *head) { if (head == NULL) { return 0; } if (head->next == NULL) { return head->data; } int data = reverse_recurse(head->next); printf("%d ", data); return head->data; }
int main(int argc, char *argv[]) { int choice; int n; int p; struct Node *head = NULL; while(1) { choice = menu(); switch(choice) { case 0: return 0; case 1: printf("Enter number: "); scanf("%d", &n); Append(&head, n); break; case 2: Display(head); break; case 3: printf("Enter number: "); scanf("%d", &n); printf("Enter position: "); scanf("%d", &p); Insert(&head, n, p); break; case 4: printf("Enter number: "); scanf("%d", &n); Delete(&head, n); break; case 5: reverse(&head); Display(head); break; case 6: reverse_recurse(head); break; default:return 0; } } return 0; }
/* * uncomment lines in body for recursive or iterative */ void reverse(LIST_ITEM ** head) { reverse_recurse (head); //reverse_iterate (head); }