Reverse

PHOTO EMBED

Sun May 14 2023 19:34:15 GMT+0000 (Coordinated Universal Time)

Saved by @prachi

#include <stdio.h>
#include <stdlib.h>

struct Node {
    char data;
    struct Node* next;
};

void addNode(struct Node* *headRef, char data) {
    struct Node* newNode = (struct Node*) malloc(sizeof(struct Node));
    
    newNode->data = data;
    newNode->next = NULL;  
 
    if (*headRef == NULL) {
        *headRef = newNode;
        return;
    }

    struct Node* currNode = *headRef;
    while (currNode->next != NULL) {
        currNode = currNode->next;
    }
 
    currNode->next = newNode;
}

void printReverse(struct Node* head) {
    if (head == NULL) {
        return;
    }
    printReverse(head->next);
    printf("%c", head->data);
}

int main() {
    struct Node* head = NULL;
    char c;
    printf("Enter a word: ");
    while ((c = getchar()) != '\n') {
        addNode(&head, c);
    }

    printf("Reverse word: ");
    printReverse(head);
    printf("\n");

    struct Node* currNode = head;
    while (currNode != NULL) {
        struct Node* nextNode = currNode->next;
        free(currNode);
        currNode = nextNode;
    }
    return 0;
}
content_copyCOPY