#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; }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter