/* * This function reverses a linked list recursively . */ void reverseRecursive(struct node **head){ struct node *first; struct node *rest; /* empty list */ if(*head == NULL){ return ; } first = *head ; rest = first->next; /* List has only one node */ if(rest == NULL){ return ; } /* reverse the rest list and put the first element at the end */ reverseRecursive(&rest) ; first->next->next = first ; first->next = NULL ; /* fix the head pointer */ *head = rest ; }
void reverseRecursive(struct node ** head) { struct node * first; struct node * rest; /*zero nodes*/ if(*head == NULL) return; first = *head; rest = first->next; /*Single node*/ if(rest == NULL) return; /*Recursion for the rest*/ reverseRecursive(&rest); //Switch the link first->next->next = first; first->next = NULL; *head = rest; }
int main() { int arr[] = {3, 4, 5, 6, 7}; std::vector<int> array(arr, arr+sizeof(arr)/sizeof(int)); struct node * head = new struct node; createLinkedList(array, &head); displayList(head); // reverse(&head); reverseRecursive(&head); displayList(head); return 0; }
int main(void) { struct node *head = NULL ; insertFirst(&head, 10); insertFirst(&head, 22); insertFirst(&head, 35); insertFirst(&head, 75); printf("Original Linked list \n"); printList(head); reverseRecursive(&head); printf("\nReversed Linked list \n"); printList(head); getchar(); }
static void reverseStringRecursive(std::string& string) { int length = string.size(); reverseRecursive(string, 0, length - 1); }
/** * Time complexity: O(n) * Space complexity: O(n) * where n is the maximum recursion depth */ static void reverseRecursive(std::string& string, int begin, int end) { if (begin < end) { std::swap(string[begin],string[end]); reverseRecursive(string, ++begin, --end); } }